ajax - Angular 2 HTTP 进度条

标签 ajax http angular ionic2

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. 4.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 .

关于ajax - Angular 2 HTTP 进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37158928/

相关文章:

Python 在发送文件前保持 HTTP 连接?

javascript - jquery ajax 调用和 j_security 重定向

php - JavaScript 与 PHP 组合

javascript - JQMobile - 无法在自定义 ajax 中加载微调器

c - VIrusTotal API 的 C 语言短语 HTTP 请求

php - 从自己的服务器运行 URL

angular - 删除 URL Angular 11 中的哈希(#)

带有 *ngFor、双向绑定(bind) [(ngModel)] 和表单验证的 angular2 动态表单

javascript - Angular2 可以在 Chrome 中工作,但不能在 Firefox 中工作

php - 对包含在同一页面上的 php 函数进行 ajax 调用