How to create XHR request in angular2?

I created an image downloader using angular2 http post request. Now I want to track the progress of the Downloadable image, which can be used with the xmlHTTP request, but I can not find the format suitable for it.

here is my code for the http image downloader.

    uploadImage(eventId:number,formData:any): Observable<any[]> {
    // update location info of an event
    let headers = new Headers({ **Some necessary headers** });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(AppSettings.API_ENDPOINT+'/events/uploads',formData, options)
        .map((response: Response) => response.json());
}

It works as expected. Now, how can I track the download progress of my image?

+4
source share
1 answer

I suppose you can do something like this in your script:

public uploaded : string;
uploadImage(eventId: number, formData: any): Observable < any[] > {
  // update location info of an event
  let headers = new Headers({ ** Some necessary headers ** });
  let options = new RequestOptions({ headers: headers });
  let xhr = this.http.post(AppSettings.API_ENDPOINT + '/events/uploads', formData, options);

  xhr.onprogress = (event) => {
     let progress = (event.loaded/event.total)*100;
     this.uploaded = progress; // update the uploaded property to show in the view
  };
  xhr = xhr.map((response: Response) => response.json());

  return xhr;
}
0
source

Source: https://habr.com/ru/post/1671564/


All Articles