Angular 2 HTTP进度条

C. *_*ans 20 ajax http ionic2 angular

目前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) => {
                ...
            });
Run Code Online (Sandbox Code Playgroud)

目标是编写同步系统.该帖子将返回大量数据,我想让用户了解同步需要多长时间.

Bar*_*cki 21

目前(从4.3.0开始,当使用new HttpClient时@ngular/common/http)Angular提供了开箱即用的进度.您只需要创建HTTPRequest对象,如下所示:

import { HttpRequest } from '@angular/common/http';
...

const req = new HttpRequest('POST', '/upload/file', file, {
  reportProgress: true,
});
Run Code Online (Sandbox Code Playgroud)

当您订阅请求时,您将在每个进度事件中收到订阅:

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!');
  }
});
Run Code Online (Sandbox Code Playgroud)

更多信息在这里.


Thi*_*ier 6

您可以利用onprogressXHR提供的事件(请参阅此plunkr:http://plnkr.co/edit/8MDO2GsCGiOJd2y2XbQk?p = preview ).

这允许获得有关下载进度的提示.Angular2不支持此功能,但您可以通过扩展BrowserXhr类来插入它:

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  constructor(private service:ProgressService) {}
  build(): any {
    let xhr = super.build();
    xhr.onprogress = (event) => {
      service.progressEventObservable.next(event);
    };
    return <any>(xhr);
  }
}
Run Code Online (Sandbox Code Playgroud)

并BrowserXhr使用扩展覆盖提供者:

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此问题: