代码之家  ›  专栏  ›  技术社区  ›  iamcootis

调用onDestroy后返回异步调用

  •  0
  • iamcootis  · 技术社区  · 5 年前

    我有一个异步服务器调用,它是这样设置的。对呼叫的响应会设置一个计时器,在30秒内再次呼叫自己。如果用户离开页面,则会出现问题。即使调用了this.stopTimer(),如果离开页面后返回响应,循环也会继续。我如何防止在调用了n 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;
    }
    
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   Thierry Falvo    5 年前

    你可以考虑这种方法。

    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秒的延迟。

    可观察 destroy$ 为您提供了因用户操作或组件损坏而取消轮询的功能。