在同一.map输出

时间:2017-12-15 01:56:21

标签: angular rxjs5

我有一个JSON数据集,其中包含我需要通过键找到的多个值。我是rxjs运算符的新手,想要实现类似下面的代码示例但不确定如何。

我知道为什么这个代码示例不起作用,因为第二个过滤器操作符正在接收来自前一个过滤器值的已过滤值...但是,此代码示例最终说明了我试图实现的内容。

  • 有没有办法以某种方式嵌套运算符以确保两个过滤器 运算符从地图运算符接收相同/原始输出?

在我看来,必须有一种方法可以避免再次运行.map运算符只是为了运行第二个过滤器...我只是不知道该怎么做。

.map(res=>JSON.parse(res))
      .filter(res=>res.filterValue1).do(res=>console.log(res))
      .filter(res=>res.filterValue2).do(res=>console.log(res))
      .subscribe()

附加信息:JSON对象包含多个参数值对,我想使用点表示法找到它们,并通过组件中的.do运算符分配局部变量。请参阅下面的新示例。

这可能会让我对如何真正利用运营商管道感到困惑,但我试图避免多个.map JSON.parse事件。

第一个过滤行中的点符号正常工作,因为它找到参数并将其设置为局部变量,但第二个不符合,因为它正在接收来自前一个.filter运算符的过滤数据流。

  • 有没有办法确保.filter运营商都收到“原创” .map运算符输出的流副本?

    .map(res => JSON.parse(res))
          .filter(res => res.favorites).do(res => this._favorites = res)
          .filter(res => res.codes).do(res => this._codes = res)
          .subscribe()
    

第二附加信息:在Chaining Operators下的reactivex.io上找到了这个信息。我猜我试图用链做什么是不可能的。听起来我必须为每个过滤条件创建一个链,并将输出分配给subscribe()中的本地变量。

对我来说似乎效率低下,但我猜它就是这样。

A chain of Observable operators do not operate independently on the original Observable that originates the chain, but they operate in turn, each one operating on the Observable generated by the operator immediately previous in the chain.

1 个答案:

答案 0 :(得分:0)

如果你想要过滤器1或过滤器2,那么语法可能如下所示:

   .map(res=>JSON.parse(res))
      .filter(res=>res.filterValue1 || res.filterValue2)
      .do(res=>console.log(res))
      .subscribe()

但是filterValue1和filterValue2是什么?他们属性?如果是这样,那么您的过滤器语法可能不正确。

以下是我的一个过滤器语句:

this.filteredProducts = this.products.filter((product: IProduct) =>
       product.productName.toLocaleLowerCase()
         .indexOf(filterValue1.toLocaleLowerCase()) !== -1) || 
       product.productName.toLocaleLowerCase()
         .indexOf(filterValue2.toLocaleLowerCase()) !== -1);

请注意,toLocalLowerCase确保在比较中情况无关紧要。