gpt4 book ai didi

javascript - Angular/RxJs 无法识别数组

转载 作者:行者123 更新时间:2023-12-03 03:50:26 25 4
gpt4 key购买 nike

我不明白为什么下面的代码不能按预期工作。

    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…]

最佳答案

问题是您正在调用的第二个 map 函数。 Map 对数据流应用转换,并应返回转换后的元素。

当前,第二个映射使用 webapi 返回的 POJO 数组,但不会将它们再次传递回流。

假设 MyDataType 是一个 typescript 接口(interface),并且包含从 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 的更多信息

关于javascript - Angular/RxJs 无法识别数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45188914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com