How should I modify the response to an HTTP request and easily access it before return it out from Observable?

前端 未结 6 461
春和景丽
春和景丽 2021-02-01 23:42

I\'m upgrading to Angular to version 5, I was using @angular/http before and now I need to update to @angular/common/http and use HttpClient

I a

6条回答
  •  北海茫月
    2021-02-01 23:51

    It all depends on the version of RxJs. Angular 6 shipped with RxJs 6 - which means that the map()/catch() approach is no longer valid.

    Instead, you have to use pipe + map()/catchError() as shown below:

    Before Angular 6 / RxJs 6 - classic Http use:

    return this.http.get(url, {headers: this.headers}).map(
      (response: Response) => {
        const data : SomeType = response.json() as SomeType;
        // Does something on data.data
    
        // return the modified data:
        return data.data; // assuming SomeType has a data properties. Following OP post
      }
    ).catch(
      (error: Response) => {
        throwError(error); // From 'rxjs'
      }
    );
    

    Should be changed to this:

    After Angular 6 / RxJs 6 - HttpClient migration:

    return this.http.get(url, {headers: this.headers})
      .pipe(
         map( response => {  // NOTE: response is of type SomeType
             // Does something on response.data
             // modify the response.data as you see fit.
    
             // return the modified data:
             return response; // kind of useless
         }),
         catchError( error => {
             return throwError(error); // From 'rxjs'
         })
      ); // end of pipe
    

    In the pipe, map() will pick up the response object (already parsed from JSON) and catchError() will pick up the first error if the HTTP fails.

    Also, note that your Headers need to be HttpHeaders object too.

    Read on pipe, map and catchError in RxJs 6

提交回复
热议问题