目前Angular 2中有一种方法可以使用angular2 / http模块检索ajax调用的进度(即完成百分比)吗?
我使用以下代码进行HTTP调用:
let body = JSON.stringify(params); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); this.http.post(url,body,options) .timeout(10000,new Error('Timeout exceeded during login')) .toPromise() .then((res) => { ... }).catch((err) => { ... });
目标是编写同步系统.该帖子将返回大量数据,我想让用户了解同步需要多长时间.
解决方法
目前(从v.3.3.0开始,当使用来自@ ngular / common / http的新HttpClient时)Angular提供了开箱即用的收听功能.您只需要创建HTTPRequest对象,如下所示:
import { HttpRequest } from '@angular/common/http'; ... const req = new HttpRequest('POST','/upload/file',file,{ reportProgress: true,});
当您订阅请求时,您将在每个进度事件中收到订阅:
http.request(req).subscribe(event => { // Via this API,you get access to the raw event stream. // Look for upload progress events. if (event.type === HttpEventType.UploadProgress) { // This is an upload progress event. Compute and show the % done: const percentDone = Math.round(100 * event.loaded / event.total); console.log(`File is ${percentDone}% uploaded.`); } else if (event instanceof HttpResponse) { console.log('File is completely uploaded!'); } });
更多信息here.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。