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.
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 .
catch( (error: Response) => { return Observable. throw(error); } );
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With