RxJS重构嵌套映射语句 [英] RxJS Refactor nested map statement

查看:83
本文介绍了RxJS重构嵌套映射语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆