加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax – Angular 2 HTTP进度条

发布时间:2020-12-16 02:44:39 所属栏目:百科 来源:网络整理
导读:目前Angular 2中有一种方法可以使用angular2 / http模块检索ajax调用的进度(即完成百分比)吗? 我使用以下代码进行HTTP调用: let body = JSON.stringify(params); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new R
目前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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读