RxJS重构嵌套映射语句 [英] RxJS Refactor nested map statement
问题描述
我有一个使用@angular/http
从API加载数据的服务.
我想使用此数据为我的Components
创建检索到的数据的投影.
I have a service which uses @angular/http
to load data from an API.
I want to create a projection of the retrieved data for my Components
using this data.
因此,我编写了以下代码:
Therefore I wrote the following code:
getById(id: string) {
return this.http
.get(`https://my-api.io/${id}`)
.map(response => response.json())
.map(contracts =>
contracts.map(contract => # <- Nested map
new Contract(
contract['id'],
contract['description']
)
)
);
}
在第6 行中,我有一个嵌套的map
语句,降低了代码的可读性.
In the 6th line I have a nested map
-Statement reducing the readability of my code.
问题
我可以做得更好吗?我可以使用RxJS中的运算符代替创建此类嵌套吗?
Can I do better? Is there an operator in RxJS which I can use instead of creating this kind of nesting?
提前谢谢!
推荐答案
I propose to use flatMap/selectMany to flatten your nested array into a new stream of each single array element. In a next step you can then use RxJS.map()
to do the actual mapping. Finally collect all mapped array elements with RxJS.toArray()
into a new observable that provides a single array event:
const stream = $http('http://jsonplaceholder.typicode.com/posts')
.map(res => res.data)
.flatMap(posts => posts)
.map(post => Object.assign({}, post, { status: false }))
.toArray();
在此处查看示例: http://jsbin.com/vigizihiwu/1/edit? js,控制台
但我还要考虑:真的需要做这样的事吗?如果您只有一个订阅者,则将接收到的数组映射到那里:
But I would also consider: is doing such limbo really necessary? If you only have one subscriber at all, map the received array there:
const stream = $http('http://jsonplaceholder.typicode.com/posts')
.map(res => res.data);
stream.subscribe(res => {
const posts = res.map(post => Object.assign({}, post, { status: false }));
console.log(posts);
});
这篇关于RxJS重构嵌套映射语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!