Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 533
Zze Avatar asked Feb 01 '18 11:02

Zze


1 Answers

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))));
}
like image 102
Igor Avatar answered Nov 15 '22 07:11

Igor