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.
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:And when you subscribe to to request you will get subscription called on every progress event:
More info here.
I strongly recomend using this
https://www.npmjs.com/package/angular-progress-http
otherwise messing around with xhr will make you miss sessions cookies and other stuffs
besides it'll be more portable and way easier to implement
When you make http cals in angular2, it returns an Observable of type Response, this response is created inside class called XHRConnection where all the magic happens.
The XHRConnection builds the response by listening to XMLHttpRequest's load event, this means it will return one response at the end of the request.
Now to be able to alter this behavior we need to make our connection class listen to the progress event.
So we need to create custom Connection class, to handle the response as we see fit.
I did it this way, Take note that my php API returns multi response in a single request and this responses are plain strings.
my_backend.ts
And in the app.component.ts
Now calling http.get will return a steam of responses.
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:and override the
BrowserXhr
provider with the extended:See this question for more details: