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