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

路线以角度2变化时的结束间隔

  •  7
  • daniel  · 技术社区  · 8 年前

    我在路由器出口内的Angular 2组件中启动计时器。

    setInterval(() => {
        ...
    }, 10000);
    

    当我离开嵌入组件的路线时,计时器不会退出。我如何才能做到这一点?

    3 回复  |  直到 8 年前
        1
  •  21
  •   inoabrian    8 年前

    你可以从这个钩子上清除间隔。 我的从组件/视图控制。

    export classTestInterval implements OnInit, OnDestroy{
         public timerInterval:any;
         ngOnInit(){
           // Need interval scope in the component could be from somewhere else, but we need scope to be able to clear it on destruction of component.
           this.timerInterval = setInterval(function(){...},10000);
         }
         ngOnDestroy() {
            // Will clear when component is destroyed e.g. route is navigated away from.
            clearInterval(this.timerInterval);
         }
    }
    
        2
  •  9
  •   Sasxa    8 年前

    这应该做到:

    routerOnActivate() {
      this.timer = setInterval(()=>{
                    ...
                }, 10000);
    }
    
    routerOnDeactivate() {
      clearInterval(this.timer);
    }
    
        3
  •  6
  •   martin    8 年前

    也许你想要的更好 OnDeactivate 从…起 angular2/router (也许还有 OnActivate 取决于您的用例),因为您说过如果我理解正确,您希望在用户离开路线时结束计时器。

    export Compnent implements OnInit, OnDeactivate {
        private timer;
    
        ngOnInit(){
            this.timer = setInterval(_ => {
                // disco
            }, 10000);
        }
    
        routerOnDeactivate() {
            clearInterval(this.timer);
        }
    }