Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 HTTP Progress bar

Is there currently a way within Angular 2 to retrieve the progress (i.e. percentage done) of an ajax call, using the angular2/http module?

I use the following code to make my HTTP calls:

        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) => {
                ...
            });

The goal is to write a synchronisation system. The post will return a lot of data, and I want to give the user an indication on how long the syncing will take.

like image 429
C. Sysmans Avatar asked May 11 '16 09:05

C. Sysmans


2 Answers

Currently (from v. 4.3.0, when using new HttpClient from @ngular/common/http) Angular provides listening to progress out of the box. You just need to create HTTPRequest object as below:

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

const req = new HttpRequest('POST', '/upload/file', file, {
  reportProgress: true,
});

And when you subscribe to to request you will get subscription called on every progress event:

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!');
  }
});

More info here.

like image 115
Bartek Cichocki Avatar answered Nov 03 '22 21:11

Bartek Cichocki


You could leverage the onprogress event provided by XHR (see this plunkr: http://plnkr.co/edit/8MDO2GsCGiOJd2y2XbQk?p=preview).

This allows to get hints about the progress of the download. This isn't supported out of the box by Angular2 but you can plug it by extended the BrowserXhr class:

@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);
  }
}

and override the BrowserXhr provider with the extended:

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);

See this question for more details:

  • Angular2 / RxJS - updating variable after getting data from Http observable
like image 6
Thierry Templier Avatar answered Nov 03 '22 21:11

Thierry Templier