首页 > 解决方案 > 如果没有“订阅”类型的对象,如何取消订阅 Observable?

问题描述

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

如果我有类似的东西:

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;
      }
    });

  }

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

标签: angulartypescriptobservablesubscription

解决方案


有 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();
    }
    

我希望这有帮助!


推荐阅读