Home > OS >  how to convert response body based on status code in Angular 8
how to convert response body based on status code in Angular 8

Time:10-08

The api returns 2 status code depending on file size. For 200,it returns a json string which I have converted to Object using transformImportCSVResponse(). For 201, it returns a text as response ("File upload is in progress")

Right now it's failing for 201 as it's not able to convert to json

How to process both based on status code.

this.httpClient.post(url, uploadedFile, {params: httpParams}).pipe(
      catchError(err => throwError(err)))
      .pipe(map(this.transformImportCSVResponse))

CodePudding user response:

Using map(this.transformImportCSVResponse) is unsafe as the context of transformImportCSVResponse function will not this, but something else.

this.httpClient.post(url, uploadedFile, {params: httpParams}).pipe(
  map(res => {
    if (res.status == 201) {
      return { status: 'uploading' };
    }

    return res;
  }),
  catchError(err => throwError(err)),
  map(res => this.transformImportCSVResponse(res)),
)

CodePudding user response:

The problem is that 200 and 201, actually all 2XX responsens are not treated as an error. So what You can do is:

http
  .post<T>('/yoururl', whateverYourPostRequestIs, {observe: 'response'})
  .subscribe(resp => {
     console.log(resp);
  });

Code taken from: How can get HttpClient Status Code in Angular 4

And then do if(resp.status === 200) { do thomething }

Try this code:

this.http.post(url, uploadedFile, {params: new HttpParams(), observe: 'response'})
  .subscribe(
    resp => {
      if (resp.status === 200) {
        this.transformImportCSVResponse(resp.body);
      }
    },
    error => console.log('oops', error)
  );
  • Related