【问题标题】:How to memorize previous value from stream RxJS如何从流 RxJS 中记住以前的值
【发布时间】:2018-08-14 21:16:27
【问题描述】:

我有 2 个这样的可观察对象:

return this.loaded$.pipe(
            switchMap((isLoaded: boolean) => {
                if (!isLoaded) {
                 return this.userId$;
                }
            }),
            tap((userId: string) => {
                this.store.dispatch(new MyPostsList(userId))
            }),
            filter((value: any) => value),
            take(1)
        )

我想从 Tap 部分的 $loaded 流中访问isLoaded var 我该怎么做? 有更好的方法吗?

【问题讨论】:

  • 如果isLoadedtrue,您的代码将出错,因为undefined 将返回给switchMap。要回答您的问题,您需要指明在这种情况下预期的行为。

标签: rxjs rxjs6 rxjs-lettable-operators


【解决方案1】:

您可以返回一个同时包含 userId 和 isLoaded 的对象。

return this.loaded$.pipe(
    switchMap(
      (isLoaded: boolean) => Observable.of(
        { userId: (!isLoaded ? this.userId$ : null), isLoaded }
      )
    ),
    tap(({ userId, isLoaded }) => {
      this.store.dispatch(new MyPostsList(userId))
    })
)

正如 cmets 中所指出的,我忘记了 switchMap 必须返回一个 observable。编辑了答案。

【讨论】:

  • 这会产生错误。您必须将ObservableInput 返回到switchMap
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 2015-03-07
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多