【问题标题】:How to chain observables in angular, based on condition如何根据条件以角度链接可观察对象
【发布时间】:2020-11-03 14:24:05
【问题描述】:

我在 subscribe 中有一个订阅,我想链接它,但我不确定我应该如何继续,因为实习生订阅在 if 块内。

authenticationService.isLoggedIn$.subscribe(isLoggedIn => {
  this.isLoggedIn = isLoggedIn;
  if (isLoggedIn) {
    socketService.initSocket();
    authenticationService.refresh().subscribe(time => {
      this.timeOut = time.expirationTime;
      this.setTimeout(this.timeOut);
    });
  } else {
    clearTimeout(this.userActivity);
    socketService.destroySocket();
  }
});

我很想以某种方式链接它,以便只能订阅一次。 我在想把它放在一个可以顺序运行它的数组中会很好吗?

【问题讨论】:

  • 你能详细说明一下吗?我不确定你在这里实际问的是什么。
  • 我想避免在subscribe()中有subscribe(),而是包含代码的逻辑。

标签: angular rxjs angular2-observables


【解决方案1】:

switchMap 可以解决问题。沿着这些思路:

return authenticationService.isLoggedIn$.pipe(
  tap(isLoggedIn => this.isLoggedIn = isLoggedIn),
  switchMap(isLoggedIn => isLoggedIn ? authenticationService.refresh() : of(null)))
.subscribe(time => {
  if (time) {
    this.timeOut = time.expirationTime;
    this.setTimeout(this.timeOut);
  } else {
    clearTimeout(this.userActivity);
    socketService.destroySocket();
  }
});

【讨论】:

  • 非常感谢,这就是我要找的东西,我在寻找这样的东西时找不到tap operator :)。
【解决方案2】:

您可以使用iif 运算符:

let subscribeToFirst;
const firstOrSecond = iif(
  () => subscribeToFirst,
  of('first'),
  of('second'),
);
 
subscribeToFirst = true;
firstOrSecond.subscribe(value => console.log(value));

如果您有超过 2 个选项,您可以使用手动构造 switchMap 中的 if 语句。

myObs$
  .pipe(
    switchMap(val => {
      if(a) { return obsA$ }
      else if(b) { return obsB$ }
      else { return obsElse$ }
    })
  ).subscribe();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多