角度扁平可观察流

问题描述 投票:0回答:1

我有以下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}]
angular rxjs ngx-bootstrap
1个回答
0
投票

您应该能够使用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是数组运算符(它们都以相同的方式运行)。

© www.soinside.com 2019 - 2024. All rights reserved.