繁体   English   中英

Angular / RxJs无法识别数组

[英]Angular/RxJs not recognising array

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

    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端点返回一个数组,第二个映射函数也只会被调用一次。 看起来像:

[{}, {}, {}, {}...]

难道不应该对从服务器传回的数组中的每个元素进行迭代映射吗?

以下是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是一个打字稿接口,并且包含从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映射到其属性之一来展平数组。 在这种情况下,函数的返回类型将变得非常准确。

您可以在此处找到有关操作员的更多信息

如果需要遍历由ajax调用返回的数组,则应将其包装在Observable.from函数中。 您确实需要在json之后的另一张地图,该地图不返回值,但是是可观察的。 在这种情况下,请使用flatMap。

//code omitted for brevity
.map( r : Response => r.json() )
.flatMap((obj: any) => Observable.from(obj) )

此后,数组的Observablel变为单个值的Observable。 但是我对您提供的类型一无所知,并且无法查看该类型是否是数组的包装器

我想从数组的每个元素中获取一个属性,然后返回这些属性的数组。 例如[{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})))
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM