Filter Operator谓词函数返回数组

时间:2018-05-27 04:22:22

标签: angular filter rxjs observable ngrx

我有一个Observable对象数组。每个对象都有一个'id'属性。我正在使用filter方法,目的是只返回与特定id匹配的对象的observable。

当我实现以下代码时,谓词函数返回整个数组。我的期望是只有一件物品通过。

    this.blog$ = this.store.select('posts', 'blogs').pipe(
      filter((post, index) => {
        console.log(post[index].id == this.id);
        return post[index].id == this.id
      }),
    ).subscribe(x=>console.log(x))

enter image description here

第一个控制台日志在filter函数内,第二个是从subscribe方法调用的。

如果我的比较器函数评估为真实,仅针对某个id,我怎样才能正确地产生传递对象?

2 个答案:

答案 0 :(得分:3)

rxjs过滤器函数用于过滤每个发射器,因此如果这对阵列发射一次,则需要使用阵列过滤器功能以及map而不是

this.blog$ = this.store.select('posts', 'blogs').pipe(
  map((posts) => posts.filter((post) => post.id == this.id))
).subscribe(x=>console.log(x))

或者,如果您只需要第一个匹配项,并希望将结果作为对象而不是具有1个元素的数组,那么只需使用find数组函数:

this.blog$ = this.store.select('posts', 'blogs').pipe(
  map((posts) => posts.find((post) => post.id == this.id))
).subscribe(x=>console.log(x))

答案 1 :(得分:0)

完整的rx替代方案是:

this.blog$ = this.store.select('posts', 'blogs').pipe(
  mergeAll(),
  filter(post => post.id == this.id)
).subscribe(post => console.log(post))