如果没有 "Subscription" 类型的对象,如何取消订阅 Observable?

How to unsubscribe from Observable if there is no object of type "Subscription"?

如果我订阅了一个 Observable,如果没有 "Subscription" 类型的对象,我该如何取消订阅?

如果我有类似的东西:

this.subscription = bla ... 

然后我可以按如下方式取消订阅(在 ngOnDestroy() 方法中):

this.subscription.unsubscribe();

但是如果我遇到这样的事情怎么办:

 ngOnInit() {

    this.isLoggedIn$ = this.authService.isLoggedIn();

    this.isLoggedIn$.subscribe(res => {
      if (res) {
        this.isLoggedIn = true;
      } 
      else {
        this.isLoggedIn = false;
      }
    });

  }

如何取消订阅?我什至必须退订吗?如果不是,为什么不呢?

您实际上已经在这里提供了自己的答案:bla ... 是您的 this.isLoggedIn$.subscribe( ... ) 电话。

ngOnInit() {

  this.isLoggedIn$ = this.authService.isLoggedIn();

  this.subscription = this.isLoggedIn$.subscribe(res => {
    if (res) {
      this.isLoggedIn = true;
    } 
    else {
      this.isLoggedIn = false;
    }
  });

}

取消订阅前检查this.isLoggedIn$是否存在

ngOnDestroy() {
this.isLoggedIn$ && this.isLoggedIn$.unsubscribe();
}

有 3 种方法可以取消订阅 observable

  1. 您可以使用上述方法作为 this.subscription 分配订阅 对于每个订阅,然后明确取消订阅每个。 (它 应该避免)

  2. 您可以通过示例使用 takWhile 管道 以下:

    private isAlive = true;
    
    ngOnInit() {
    
      this.isLoggedIn$ = this.authService.isLoggedIn();
    
      this.subscription = this.isLoggedIn$
       .pipe(takeWhile(() => this.alive))
       .subscribe(res => {
        if (res) {
          this.isLoggedIn = true;
        } 
        else {
          this.isLoggedIn = false;
        }
      });
    
    }
    
    
    ngOnDestroy() {
       console.log('[takeWhile] ngOnDestory');
       this.alive = false;
    }
    
  3. 使用 takeUntil 运算符:

    private unsubscribe: Subject<void> = new Subject();
    
    ngOnInit() {
    
      this.isLoggedIn$ = this.authService.isLoggedIn();
    
      this.subscription = this.isLoggedIn$
       .pipe(takeUntil(this.unsubscribe))
       .subscribe(res => {
        if (res) {
          this.isLoggedIn = true;
        } 
        else {
          this.isLoggedIn = false;
        }
      });
    }
    
    ngOnDestroy() {
      this.unsubscribe.next();
      this.unsubscribe.complete();
    }
    

希望对您有所帮助!!