簡體   English   中英

如果沒有“ 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;
    }
  });

}

取消訂閱可觀察項的3種方法

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

我希望這會有所幫助!

取消訂閱前只需檢查this.isLoggedIn $是否存在

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM