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.
因此我写了以下代码:
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
-Statement,降低了代码的可读性.
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?
提前致谢!
推荐答案
我建议使用 flatMap/selectMany 将嵌套数组展平为每个单个数组元素的新流.在下一步中,您可以使用 RxJS.map()
进行实际映射.最后使用 RxJS.toArray()
将所有映射的数组元素收集到一个提供单个数组事件的新 observable 中:
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屋!