Angular 2 setinterval()继续在其他组件上运行 [英] Angular 2 setinterval() keep running on other component

查看:175
本文介绍了Angular 2 setinterval()继续在其他组件上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个组件中具有以下方法:

I have the following method in one component:

ngOnInit()
        {
            this.battleInit();
            setInterval(() => {
                this.battleInit(); 
                }, 5000);
        }

现在,仅当用户位于该特定组件中时,我才需要运行此间隔,这意味着当用户离开该组件时,该间隔将停止.

Now, I need to run this interval only if the user is in this specific component, that means that when the user navigate away from this component the interval will stop.

当前,即使用户离开该页面,this.battleInit()也每5秒执行一次.

Currently, this.battleInit() is executed every 5 seconds, even after the user navigates away from this page.

简短的问题:当用户通过路由导航到另一个组件时,如何停止setInterval()?

Short question: How do I stop setInterval() when user navigate away (by routing) to another component?

推荐答案

您需要在组件的ngOnDestroy挂钩方法中使用clearInterval方法.为此,您需要通过setInterval方法保存返回的值.

You need to use clearInterval method for this within the ngOnDestroy hook method of your component. For this you need to save the returned value by the setInterval method.

以下是示例:

ngOnInit() {
  this.battleInit();
  this.id = setInterval(() => {
    this.battleInit(); 
  }, 5000);
}

ngOnDestroy() {
  if (this.id) {
    clearInterval(this.id);
  }
}

这篇关于Angular 2 setinterval()继续在其他组件上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆