首页 > 解决方案 > 使用 NGRX 的 RXJS 链订阅反模式

问题描述

我有以下代码,它正在工作,但我读过链接订阅是一种反模式。在调用需要用户 authtoken 的 API 之前,我需要确保用户的登录状态为 true。

在 RXJS 中处理这个问题的正确方法是什么?

const subscrAuth = this.store
  .pipe(select(isLoggedIn))
  .subscribe(isLoggedIn => {
    console.log(isLoggedIn);
    if (isLoggedIn) {
      const subscrLoaded = this.store
        .pipe(select(hasCarriersLoaded))
        .subscribe(hasCarrierLoaded => {
          if (!hasCarrierLoaded) {
            this.store.dispatch(new CarriersPageRequested());
          }
        });
    }
  });
this.unsubscribe.push(subscrAuth);

标签: angularrxjsngrx

解决方案


像这样的东西?

const subscrAuth = this.store
.pipe(
  select(isLoggedIn),
  switchMap(isLoggedIn => {
    this.store.pipe(
      select(hasCarriersLoaded),
      tap(hasCarriersLoaded => {
        this.store.dispatch(new CarriersPageRequested());
      })
     )
  })
).subscribe();
this.unsubscribe.push(subscrAuth);

我还建议使用 ngOnDestroy 函数来管理您的订阅,如下所示,

onDestroy$: Subject<null> = new Subject();

ngOnDestroy() {
    this.onDestroy$.next();
}

this.store
.pipe(
  takeUntil(this.onDestroy$),
  select(isLoggedIn),
  switchMap(isLoggedIn => {
    this.store.pipe(
      select(hasCarriersLoaded),
      tap(hasCarriersLoaded => {
        this.store.dispatch(new CarriersPageRequested());
      })
     )
  })
).subscribe();

或者,如果您只想打一个电话,您也可以像这样修改管道

this.store
.pipe(
  take(1),
  select(isLoggedIn),
  switchMap(isLoggedIn => {
    this.store.pipe(
      select(hasCarriersLoaded),
      tap(hasCarriersLoaded => {
        this.store.dispatch(new CarriersPageRequested());
      })
     )
  })
).subscribe();

推荐阅读