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

前端 未结 6 474
春和景丽
春和景丽 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:56

    In the "new" Httpclient, get return yet a json response by default. Then you only write

    import {HttpClient} from '@angular/common/http'; //<--HttpClient
    import 'rxjs/add/operator/map';                  //import the operator "map"
    import 'rxjs/add/operator/catch'; //and the operator "catch"
    
    ....
    constructor(private http: HttpClient) {} //<--sure HttpClient
    ...
    return this.http.get(url).map(  //yet get "data"
          (data:any) => {
            return this.processData(data);
          }
        ).catch(
          (error: Response) => {
            return Observable.throw(error);
          }
        );
    
    public processData(data : any){
      //process your data
      return data;//this is processed data
    }
    

提交回复
热议问题