【问题标题】:How to unsubscribe from Observable if there is no object of type "Subscription"?如果没有“订阅”类型的对象,如何取消订阅 Observable?
【发布时间】:2018-08-10 15:08:19
【问题描述】:

如果我订阅了一个 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;
      }
    });

  }

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

【问题讨论】:

  • 这里有一些关于 Angular Observables 的文档,订阅方法正在使用这些文档。至于您是否必须取消订阅,如果不了解您想要做什么,就很难说。也许文档可以提供一些见解。

标签: angular typescript observable subscription


【解决方案1】:

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

我希望这有帮助!

【讨论】:

    【解决方案2】:

    您实际上已经在这里提供了自己的答案: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;
        }
      });
    
    }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多