调用onDestroy后返回异步调用

时间:2020-03-11 20:36:21

标签: angular observable

我有一个这样设置的异步服务器调用。响应呼叫,设置了一个计时器,以在30秒内再次呼叫自己。如果用户导航离开页面,则会出现问题。即使已调用this.stopTimer(),如果在离开页面后返回了响应,循环也会继续。如何防止在调用ngOnDestroy()之后调用下一个this.startTimer()?

ngOnInit() {
    this.doSomething();
}

ngOnDestroy(){
    this.stopTimer();
}

doSomething() {
         var me = this;

        this.stopTimer();
        this.service.getStuff().subscribe(
            (response: any) => {

                ...do stuff
                this.startTimer();

            }
        )
    }

startTimer() {
    var me = this;
    clearTimeout(me.timeoutHandle);
    me.timeoutHandle = setTimeout(function () {
        me.doSomething();
    }, 30000);
}

stopTimer() {
    var me = this;
    clearTimeout(me.timeoutHandle);
    me.timeoutHandle = null;
}

1 个答案:

答案 0 :(得分:1)

您可以考虑采用这种方法。

destroy$ = new Subject<boolean>();

ngOnInit() {
  this.startPolling();
}

ngOnDestroy(){
  this.destroy$.next(true);
}

startPolling() {
  this.service.getStuff().pipe(
    tap(response => {
      //... do stuff
    }),
    delay(30 * 1000),  // wait for 30s before retry
    repeat(),
    takeUntil(this.destroy$),
  ).subscribe();
}

请注意,在这种情况下,如果后端需要一些时间来返回响应,则自从收到响应起,将延迟30秒。

Observable destroy$使您能够取消由于用户操作或组件被破坏时的轮询。

相关问题