Angular HttpClient-rxjs映射-到类型数组 [英] Angular HttpClient - rxjs map - to an array of Type
问题描述
我有以下HttpClient.post
调用,它们返回一个对象数组.
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;
}));
}
我需要实例化对象数组.我不能只输入assert,因为我需要Thing
构造函数来解析一些json
和其他.
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.
基本上我想做的是:
.pipe(map(data => {
console.log(data); // logs (2) [{…}, {…}]
return data.map(v => new Thing(v));
}));
但是,我不能(据我所知),因为data
是类型ArrayBuffer
,并且不可迭代.我该如何实现?
However I can't (to my knowledge) because data
is of Type ArrayBuffer
and is not iterable. How can I achieve this?
推荐答案
实际上如何从服务器发送数据?是json
还是其他?如果是json
,请尝试在HttpClient
的调用中进行指定(请参阅文档)使用options
参数中的responseType:'json'
.
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))));
}
这篇关于Angular HttpClient-rxjs映射-到类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!