Angular HttpClient - rxjs map - to an array of Type

拈花ヽ惹草 提交于 2019-12-23 09:26:15

问题


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?


回答1:


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))));
}


来源:https://stackoverflow.com/questions/48562160/angular-httpclient-rxjs-map-to-an-array-of-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!