Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角组件每X秒刷新一次页面上的数据_Javascript_Angular_Single Page Application - Fatal编程技术网

Javascript 角组件每X秒刷新一次页面上的数据

Javascript 角组件每X秒刷新一次页面上的数据,javascript,angular,single-page-application,Javascript,Angular,Single Page Application,我需要每30秒刷新一次角度分量的数据。我使用simplesetInterval: this.interval = setInterval(() => { this.refresh(); // api call }, 10000); 然而,这是不正确的,因为即使我导航到另一个“页面”(在angular SPA中,所有内容都是一个页面,因此它实际上不是另一个页面),刷新也会每30秒发生一次 仅当在特定页面/组件上时,每30秒刷新一次数据

我需要每30秒刷新一次角度分量的数据。我使用simple
setInterval

 this.interval = setInterval(() => {
               this.refresh(); // api call
            }, 10000);
然而,这是不正确的,因为即使我导航到另一个“页面”(在angular SPA中,所有内容都是一个页面,因此它实际上不是另一个页面),刷新也会每30秒发生一次

仅当在特定页面/组件上时,每30秒刷新一次数据的正确方法是什么?

试试这个

routerOnActivate() {
   this.interval = setInterval(() => {
               this.refresh(); // api call
            }, 10000);
}

routerOnDeactivate() {
  clearInterval(this.interval);
}

您可以在
ngondestory
组件的生命周期钩子中清除间隔

ngOnDestroy() {
  clearInterval(this.interval);
}
ngondestory
将在摘要周期中的每次组件销毁时调用,它也将清除您的间隔(如果您这样做)。 通常用于在当前路线导航到另一条路线后调用我们不需要的逻辑


您可以在组件的生命周期挂钩上销毁interval

使用
clearInterval(this.interval)


当您导航到另一页时,必须清除正在设置的间隔

this.interval = setInterval(()=>{
  ...
});

navigateToAnotherPage = () => {
  //function to navigate to another page
  clearInterval(this.interval);
  router.navigate(...)//if you are using router to navigate
}

试试这个。

save: boolean = false;
autoSave() {
        setInterval(() => {
            console.log('setTimeOut');
            this.save = true;

        }, 1000);
}

这篇文章将帮助您:什么是
导航到另一个页面
?什么时候调用?提问者使用什么导航到另一页。可能是使用
路由器进行导航的函数调用。导航
。不确定导航是如何发生的,因为OP中没有提到它。@PardeepJain,但我同意你的解决方案
Ngondestory
似乎是一个更通用的解决方案。谢谢,但这并不是特定角度的问题。似乎与我的答案更相似。我知道,因为我们是在同一时间编写的,更多更少。顺便说一句,您还可以提到组件应该实现OnDestroy。。。否则ondestroy永远不会调用,对吗?是的,对于编辑器,您应该实现
ondestroy
,这是最好的方法。对于最终结果,您可以避免它,因为在运行时Javascript会丢失用Typescript声明的接口。但最好的做法是插入它。
save: boolean = false;
autoSave() {
        setInterval(() => {
            console.log('setTimeOut');
            this.save = true;

        }, 1000);
}