我无法理解为什么下面的代码没有按预期工作。
public GetX(): Observable<MyDataType> {
return this.http.get('http://localhost:64113/api/endpoint')
.map((r: Response) => r.json())
.map((r) => r.someProperty)
.catch(error => Observable.throw(error));
}
问题是即使我从.Net Core WebAPI端点返回一个数组,第二个map函数也只被调用一次。它看起来像:
[{}, {}, {}, {}...]
是否应该迭代遍历从服务器传回的数组中的每个元素?
以下是console.log
的结果(124) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object…]
答案 0 :(得分:1)
问题是您正在调用的第二个地图功能。 Map将转换应用于数据流,并应返回转换后的元素。
目前,第二张地图会消耗您的webapi返回的POJO数组,但不会再将它们传回流数据流。
假设MyDataType
是一个typescript 接口并且包含来自webapi的返回JSON对象的匹配属性,您可以使用以下命令打印服务器响应:
return this.http.get('http://localhost:64113/api/endpoint')
.map(r => r.json())
.do(r => console.log(r))
.catch(error => Observable.throw(error));
更新:如果要映射数组中每个元素的属性,则应使用mergeMap
return this.http.get('http://localhost:64113/api/endpoint')
.map(r => r.json()) // map to json body
.mergeMap(r => r) // flatten array
.map(e => e.property) //map singular objects to a property
.catch(error => Observable.throw(error));
MergeMap
将通过将每个单数POJO映射到其中一个属性来展平数组。在这种情况下,函数的返回类型将再次完全准确。
您可以找到有关运营商here
的更多信息答案 1 :(得分:0)
如果需要迭代ajax调用返回的数组,则应将其包装在Observable.from函数中。你需要在json之后的另一个地图,一个不返回值的地图,但是一个可观察的地图。在这种情况下使用flatMap。
//code omitted for brevity
.map( r : Response => r.json() )
.flatMap((obj: any) => Observable.from(obj) )
在此之后,数组的Observablel成为单个值的Observable。但是我不知道你提供的类型,并且无法看到类型是否是数组的包装
答案 2 :(得分:0)
我想从数组的每个元素中获取一个属性并返回这些属性的数组。例如
[{property:1}, {property:2}, {}, {}...]
然后我建议你像下面这样做,我们在数组上使用map并使用Object.assign
public GetX(): Observable<MyDataType> {
return this.http.get('http://localhost:64113/api/endpoint')
.map((r: Response) => r.json().map((x:any) => Object.assign({propertyName: x.property})))
}