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

Viewed 237

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))

3 Answers

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

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)),
)

Create two different streams depending upon response status using RxJs Partition operator.

import { partition, map, catchError } from 'rxjs/operators';

const [csvResponse$, otherResponse$] = 
    this.httpClient.post(url, uploadedFile, {params: httpParams}).pipe(
        catchError(err => throwError(err)),
        partition(res => res.status === 200)
    );

csvResponse$.pipe(
    map(resp => this.transformImportCSVResponse(resp))
).subscribe(csvTranformedResponse => console.log(csvTranformedResponse));

otherResponse$.subscribe(otherResp => console.log(otherResp));

I have not tested this code

Related