簡體   English   中英

用戶打開彈出窗口時如何停止輪詢?

[英]How do i stop polling when user opens a popup?

 update(){
    this.timeInterval = interval(2000).pipe(startWith(0), switchMap(() => this.deviceService.getDeviceList())
    ).subscribe((success: any) => {
      this.rowData = success;
      console.log("hello")
    },
    retry(2)
    );
  }

我有這段代碼,它每 2 秒獲取一次詳細信息。 但是我想在用戶打開任何彈出窗口時暫停此方法,並在關閉彈出窗口后再次啟動它。 不明白如何在 angular 中實現這一點?

您可以使用skipWhile rxjs 運算符,並像建議的評論一樣,在彈出可用時將標志設置為 true,然后在沒有彈出時將其刪除:

popOpen = false;

update(){
  this.timeInterval = interval(2000)
   .pipe(startWith(0), 
         skipWhile(() => this.popupOpen),
         switchMap(() => this.deviceService.getDeviceList())
  ).subscribe((success: any) => {
    this.rowData = success;
    console.log("hello")
  },
  retry(2)
);
}

看到這個stackblitz ,它顯示了這個想法

用戶takeUntillrepeatWhen來實現這一點。 如果您使用this.flag$.next(false)調用 flag$,它將停止。 要恢復,您需要使用this.flag$.next(true)調用。 檢查stackblitz以獲得更多清晰。

flag$: Subject<boolean> = new Subject<boolean>();

this.timeInterval = interval(2000)
      .pipe(
        startWith(0),
        switchMap(() => this.getUsers())
      )
      .pipe(
        takeUntil(this.flag$),
        repeatWhen(() => this.flag$)
      )
      .subscribe((success: any) => {
        console.log(success);
      }, retry(2));

這里是 stackblitz 示例: https://stackblitz.com/edit/angular-ivy-cisbks?file=src/app/app.component.ts

暫無
暫無

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

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