我有下面的Angular代码,它调用一个返回可观察对象的服务
this.dataSource = Observable.create((observer: any) => {
observer.next(this.asyncSelected);
})
.pipe(
mergeMap((token: string) =>
this._animalSuffixesServiceProxy.getAll(token, undefined, undefined, undefined)
)
);getAll方法返回以下格式的可观察对象:
{"result":{"totalCount":2,"items":[{"animalSuffix":{"name":"Test","id":1}},{"animalSuffix":{"name":"Test2","id":2}}]}}假设无法更改getAll的工作方式,我想知道如何最好地通过可观察运算符传递此响应,这样我就可以得到一个扁平化的可观察对象,如下所示:
[{"name":"Test","id":1},{"name":"Test2","id":2}]发布于 2019-04-09 09:38:12
您应该能够使用map运算符将响应处理为所需的格式。它应该如下所示:
this.dataSource = Observable.create((observer: any) => {
observer.next(this.asyncSelected);
})
.pipe(
mergeMap((token: string) =>
this._animalSuffixesServiceProxy.getAll(token, undefined, undefined, undefined)
),
map(response => response.result.items.map(item => item.animalSuffix))
);这会将您的响应映射到一个条目数组,每个条目的值就是响应条目的animalSuffix值。
pipe()中的map是映射到可观察对象上发出的每个项的RxJS操作符。另一个map是数组操作符(它们的行为方式相同)。
https://stackoverflow.com/questions/55583669
复制相似问题