我有以下Angular代码调用返回Observable的服务
this.dataSource = Observable.create((observer: any) => {
observer.next(this.asyncSelected);
})
.pipe(
mergeMap((token: string) =>
this._animalSuffixesServiceProxy.getAll(token, undefined, undefined, undefined)
)
);
getAll
方法以下列格式返回一个observable:
{"result":{"totalCount":2,"items":[{"animalSuffix":{"name":"Test","id":1}},{"animalSuffix":{"name":"Test2","id":2}}]}}
假设改变getAll
的工作方式不是一个选项,我想知道如何通过可观察的运算符来最好地管理这个响应,所以我最终得到一个扁平的observable,如下所示:
[{"name":"Test","id":1},{"name":"Test2","id":2}]
您应该能够使用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
值。
map
中的pipe()
是RxJS运算符,用于映射可观察量上发出的每个项目。另一个map
是数组运算符(它们都以相同的方式运行)。