angular: HttpClient map response

2020-02-23 06:01发布

问题:

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.

回答1:

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


回答2:

Since Angular 6/7 there have been a couple of modifications to the implementation of the RxJS library within Angular.

Hence, the RxJS operators are now located at 'rxjs/operators' instead of 'rxjs/add/operator/:OperatorName'. Also, these operators can no longer be directly chained to the observebale, instead they have to be chained through the pipe() method.

So, the new way of implementing this must look like this:

import {map} from 'rxjs/operators';

this.http.get(...)
  .pipe(
    map( response => {
     // TODO: Do Your Staff Here! 
   } )
  );

Please, refer to the specific Angular's documentation here for more details. * Here I'm assuming that your HttpClient component is available under this.http prop.



回答3:

You still can, but you need to import the map()-operator from rxjs like this:

import 'rxjs/add/operator/map';

And you will have the map() operator.

(See also my answer here: https://stackoverflow.com/a/48323851/348841)



标签: angular