Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular: HttpClient map response

Tags:

angular

Currently I'm switching from http (@angular/http) to HttpClient (@angular/common/http) and have problems mapping my response to objects.

Old code (was working before)

this.http.get(environment.baseUrl + '/api/timeslots')             .map((response: Response) => {                     const data = response.json();                     const timeslots = Array.of<Timeslot>();                     for (const item of data) {...} 

New code, but compilation error:

this.httpClient.get(environment.baseUrl + '/api/timeslots')                 .map((response: Response) => {                         const data = <Timeslot[]> response; const timeslots = Array.of<Timeslot>();                     for (const item of data) {...} 

Do I miss a cast? The response is an array of Timeslots.

like image 311
netshark1000 Avatar asked Sep 26 '17 09:09

netshark1000


People also ask

How do you handle errors when http Fails?

When the error occurs in the HTTP Request it is intercepted and invokes the catchError . Inside the catchError you can handle the error and then use throwError to throw it to the service. We then register the Interceptor in the Providers array of the root module using the injection token HTTP_INTERCEPTORS .

How would you write code to modify the response from an HTTP GET?

catch( (error: Response) => { return Observable. throw(error); } );

What is HttpClient in angular?

What Is HttpClient? HttpClient is a built-in service class available in the @angular/common/http package. It has multiple signature and return types for each request. It uses the RxJS observable-based APIs, which means it returns the observable and what we need to subscribe it.


1 Answers

Default value that returns new HttpClient is Object. It automatically calls response.json() internally.

You can tell HttpClient what type the response will be, so:

this.httpClient.get<Timeslot[]>(...)  .map((timeSlots) => {    ... 

where timeSlots's type will be Timeslot[]

See more information about typecheking in new HttpClient

  • https://angular.io/guide/http#typechecking-the-response
like image 90
yurzui Avatar answered Sep 18 '22 15:09

yurzui