【问题标题】:RxJS filter an observable with value in another ObservableRxJS 用另一个 Observable 中的值过滤一个 observable
【发布时间】:2021-05-06 17:23:45
【问题描述】:

我正在寻找最好的 RxJs 方法来过滤具有另一个值的 Observable。

首先,我有一个 observable,其中包含一个来自路由 Params 的代码。假设它是股票代码中的“BTC”

然后我有一个可观察的商店,它在 fullCoinList$ 中返回一个硬币列表(其中 1414 个)

我希望 this.coin$ observable 仅包含 this.fullCoinList$ observable 中的项目,该项目在代码名称中的某处包含字符串“BTC”。

FullCoinList$ 看起来像这样。

  [{ticker: "ETHBTC", price: "0.04597600"}
   {ticker: "LTCBTC", price: "0.00457100"}
   {ticker: "BNBBTC", price: "0.01008450"}
   {ticker: "NEOBTC", price: "0.00163300"}
   {ticker: "QTUMETH", price: "0.00541200"}
   {ticker: "EOSETH", price: "0.00229400
   .... + 1408more]

我的 NgOnInit 看起来像这样

ngOnInit(): void {
    this.activatedRoute.paramMap.subscribe( (params: ParamMap) => {
      this.ticker$ = of(params.get('ticker'))
    })

    this.fullCoinList$ = this.store.pipe(select(selectAllCoins))
    
    this.coins$ = this.fullCoinList$.pipe(
      filter( coin => coin.ticker.includes(this.ticker$)) // this line needs work
    )
  }

这是 mergeMap、concatMap 或类似的好用例吗?我将如何最好地实施它?我也不确定 include 是不是正确的方法。

编辑:我添加了一个 stackBlitz Blitz

【问题讨论】:

    标签: angular rxjs ngrx


    【解决方案1】:

    我会使用combineLatest 来组合两个可观察对象并从那里开始。

    import { combineLatest } from 'rxjs';
    import { map } from 'rxjs/operators';
    ...
    ngOnInit(): void {
        // we can get rid of a subscription here and assign it to the observable directly
        this.ticker$ = this.activatedRoute.paramMap.pipe(
          map(paramMap => paramMap.get('ticker')),
        );
    
        this.fullCoinList$ = this.store.pipe(select(selectAllCoins))
        
        this.coins$ = combineLatest(this.fullCoinList$, this.ticker$).pipe(
          // the filter is the array filter and not rxjs filter
          map(([fullCoinList, ticker]) => fullCoinList.filter(fullCoin => fullCoin.ticker.includes(ticker))),
        );
      }
    

    类似的东西应该可以工作。

    【讨论】:

    • 谢谢。我无法让它工作。我添加了一个 stackBlitz,但我似乎仍然无法正确过滤列表。
    • 其实我的错。看起来我只需要将ticker$ 更改为大写。谢谢
    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多