【问题标题】:forkJoin for multiple NgRx Store subscriptionforkJoin 用于多个 NgRx Store 订阅
【发布时间】:2018-10-17 07:07:43
【问题描述】:

我在一个数组中有多个商店订阅,我想仅在所有可观察对象都返回结果时使用 forkJoin 来获取结果。 类似的东西:

this.subscriptionsArray = this.store.select('state')
forkJoin(this.subscriptionsArray).subscribe(sub => {
  // do something here with response
});

问题是商店没有发出任何东西。

我在 GitHub 存储库上找到了解决方案:

this.subscriptionsArray = this.store.select('state').pipe(first())

这项工作,但我需要最后发出的结果,而明显的解决方案不起作用。以下代码不起作用:

this.subscriptionsArray = this.store.select('state').pipe(last())

【问题讨论】:

  • combineLatest 怎么样?它在所有可观察对象 emit 时发出。 forkJoin 在所有可观察对象完成时发出。

标签: angular observable ngrx


【解决方案1】:

在我看来,您的 observable 不是 fire and forget 类型,因此您无法获得最后发出的值,因为:

在完成时发出从源发出的最后一个值,基于 提供的表达式。

参考:last filtering operator

你应该试试combineLatest:

当任何 observable 发出一个值时,发出每个 observable 的最新值。

combineLatest(...this.subscriptionsArray).subscribe(value => console.log(value))

【讨论】:

    【解决方案2】:

    您可以使用withLatestFrom 运算符,因此您的代码可以是:

    const sub = this.store.select(selectStore1).pipe(
      first(),
      withLatestFrom(this.store.select(selectStore2).pipe(first())),
      concatMap(([selectStore1, selectStore2]) => {
        // do something
      })
    )
    

    【讨论】:

      猜你喜欢
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      相关资源
      最近更新 更多