簡體   English   中英

取消訂閱RxJS之后是否可以重新訂閱?

[英]Is there a way to re-subscribe after unsubscribing RxJS?

這是一個示例代碼,該代碼訂閱Http請求並在單擊頁面時將其取消。 如果我再次執行點擊,我想重新訂閱。

如何切換訂閱? 小提琴

export class AboutComponent implements OnInit {
constructor(private http:HttpClient){
}

flag=true;
documentclick = fromEvent(document, 'click');

 private data = {
    name:  'Samurai',
    profession:  'Developer'
  };
  ngOnInit(){

    let subscription:Subscription = this.getGoogle()   )
    .subscribe((res)=> {
     console.log(res);
   })

    this.documentclick.subscribe( e=>{
      if(this.flag){
        subscription.unsubscribe();
      }
      else{
        subscription = this.getGoogle().subscribe((res)=> {
          console.log(res);
        });
      }
      this.flag != this.flag;

    });
  }

getGoogle(): Observable<any> {
    return   this.http.get( 'https://jsonplaceholder.typicode.com/todos/1').pipe ( delay( 2000 ) )
  }

}

使用上面的代碼,如果我在2秒內單擊頁面,便可以取消請求。 但我無法再次點擊再次訂閱。

另外,如果有人可以告訴我我是否真的用unsubscribe()取消了http請求,那將是很好的選擇? 還是只是一種幻想? 如果我退訂2秒,請求會到達服務器嗎?

您的代碼有邏輯錯誤,我認為只是一個錯字。

this.flag != this.flag;

你可能是說

this.flag = !this.flag;

順便說一句(與您的問題無關),您獲得文檔點擊的方法是一種非角度的方式,您可能會遇到頁面未更新的問題。 考慮改用HostListener:

@HostListener('document:click', ['$event'])
clicked(event) {
    ..
}

取消訂閱HTTP請求應取消該請求。 但是,您無法確定是否確實將請求傳遞給服務器,因此無法保證-取消訂閱時服務器可能已經答復過。

這是清理過的stackblitz: https ://stackblitz.com/edit/angular-fzlzcf

暫無
暫無

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

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