Zze
Zze

Reputation: 18805

Angular HttpClient - rxjs map - to an array of Type

I have the following HttpClient.post call which return an array of Objects.

import { map } from 'rxjs/operators/map';

public getArray(profileId: number): Observable<any> {
    return this.http.post("/api/url", postObject, HttpSettings.GetDefaultHttpRequestOptions())
        .pipe(map(data => { 
          console.log(data); // logs (2) [{…}, {…}]
          return data;
        }));
}

I need to Instantiate an Array of objects. I can't just type assert because I need the Thing constructor to parse some json and other.

Essentially what I want to do is:

.pipe(map(data => { 
      console.log(data); // logs (2) [{…}, {…}]
      return data.map(v => new Thing(v));
    }));

However I can't (to my knowledge) because data is of Type ArrayBuffer and is not iterable. How can I achieve this?

Upvotes: 6

Views: 13527

Answers (1)

Igor
Igor

Reputation: 62213

How is the data actually sent from the server? Is it json or something else? If it is json try specifying that in the HttpClient's call (see documentation) using responseType:'json' in the options parameter.

import { map } from 'rxjs/operators/map';

public getArray(profileId: number): Observable<Thing[]> {
    var options = HttpSettings.GetDefaultHttpRequestOptions();
    options.responseType = 'json';

    return this.http.post("/api/url", postObject, options)
        .pipe(map(data => data.map(v => new Thing(v))));
}

Upvotes: 12

Related Questions