展平可观察的

时间:2016-10-07 10:13:30

标签: angular rxjs5 ngrx

我尝试根据路由参数从{ key: "321" }获取特定的 ,例如ngrx/store。我得到了这样的工作:

this.route.params
  .map((params: any) => params.key)

  .mergeMap((key: string) => {

    return this.store.select(state => state.items)

      .mergeMap((items: Observable<any[]>) => items)

      // .do(item => console.log(item, key))

      .filter((item: any) => item.key === key);
  })
  .take(1)
  .subscribe(console.log);

其中state.items是一个对象数组,例如:[ {key: "1"}, {key: "2"}, ...]随着时间的推移而填充。

我想知道有更好/不同的方法吗?

另外,为什么我会在state.items.length之前获得相同的项目多次(.take(1))?

1 个答案:

答案 0 :(得分:1)

代码已经相当不错了,但内部mergeMap并不是必需的。如果我理解正确的话,过滤器实际上应该是一张地图。您在store.select语句中获取了一系列项目,并且在过滤器中,您一次只能处理一个项目。这不应该工作,因为它是您正在处理的阵列。使用地图,我们可以将项目数组作为输入,并返回实际上是我们正在寻找的项目。

this.route.params
  .map((params: any) => params.key)
  .mergeMap((key: string) => {
      return this.store.select(state => state.items)

         // no need for this mergeMap
         //.mergeMap((items: Observable<any[]>) => items)

         // map will actually get an array of items as input here
         // we want to get the element from the array matching 
         // the key from the route param and return the first element
         // => [0] since there should be only one
         .map((item: any[]) => items.filter((item) => item.key === key)[0];
})
.take(1)
.subscribe(console.log);

Jsbin与模拟的工作示例:http://jsbin.com/sihina/7/edit?js,console

相关问题