HttpRequest and reportProgress not working or messing up my requests

tommueller picture tommueller · Apr 16, 2018 · Viewed 12.1k times · Source

I am implementing a file upload service with Angular 5 and I want to give the user some feedback on the upload progress. I found several pages suggesting to use the reportProgress parameter that comes with Angulars HttpClient, but I cannot get it working.

I use a wrapper class for all my http-requests, which then does some logic and finally all requests end up in the same method that's being called:

public request(request: HttpRequest<any>, options?: any): Observable<any> {
  return this.httpClient.request(request.method, request.url, {
    body: request.body,
    headers: request.headers,
    responseType: request.responseType,
    ...options
  });
}

I then pass a upload (post) call to it, with { reportProgress: true } as options. This did not work at all, nothing on the request changed. So I suspected, that I actually need to use the reportProgress-parameter in the HttpRequest constructor to make it work and changed my code accordingly:

public request(request: HttpRequest<any>, options?: any): Observable<any> {
  return this.httpClient.request(
    new HttpRequest(request.method, request.url, request.body, {
      headers: request.headers,
      responseType: request.responseType,
      ...options
    })
  );
}

This leads to the even more weird behavior, that now no matter what my options look like, I always only receive {type: 0} as response from the request.

What am I overseeing? I use Angular 5.1.1 and I am really a bit puzzled here right now.

So to give an explicit example, right now I receive the same response for those two HttpRequests:

{  
  "url":"http://127.0.0.1:8888/test",
  "body":{  
   "data":"testdata"
  },
  "reportProgress":false,
  "withCredentials":false,
  "responseType":"json",
  "method":"POST",
  "headers":{ some-headers ... }
}

and this request:

{  
  "url":"http://127.0.0.1:8888/api/pages",
  "body":{  
    "pageUrl":"http://localhost:1234/"
  },
  "reportProgress":true,
  "withCredentials":false,
  "responseType":"json",
  "method":"POST",
  "headers":{ some-headers ... }
}

Answer

Sam B picture Sam B · Apr 16, 2018

This method may help

public progress: number = 0;
public message: string = "";

constructor(private http: HttpClient) {}

onSubmit() {
    // replace with your request data
    const formModel = this.userForm.value;
    let formData = new FormData();

    formData.append("upload", formModel.upload);

    const uploadReq = new HttpRequest('POST', 'api/Upload', formData, {
        reportProgress: true,
    });

    this.http.request(uploadReq).subscribe((event) => {
        if (event.type === HttpEventType.UploadProgress) {
            this.progress = Math.round(100 * event.loaded / event.total);
        }
        else if (event.type === HttpEventType.Response) {
            this.message = event.body.toString();
        }
    });
}