每10秒调用一次函数Angular2 [英] Call a function every 10 seconds Angular2

查看:135
本文介绍了每10秒调用一次函数Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个计时器,每隔10秒调用 API调用,我正在使用 setTimeOut 但事实是它变成了一个无限循环,即使我推到另一个页面,它也会继续加入if条件。

I'm trying to create a Timer that calls an API call every 10 seconds, I'm using setTimeOut but the thing is that it becomes an infinite loop, and even if I push to another page it keeps joining the if condition.

示例:

我在一个方法上调用此方法来启动10秒API调用

I call this on a method to start the 10 seconds API calls

setTimeout(() => {
    this.onTimeOut();
}, 1000);

这是 onTimeOut()方法...

onTimeOut() {
    this.ApiCall().then(
    success => {
    if(success ['ok'] == 0){
        this.navCtrl.push(myPage);
    }
    },
    error => { console.log(error); });
}
setTimeout(() => {
    this.onTimeOut();
}, 1000);
}

我听说过去抖 rxjs / rs 但是我不熟悉它们,你能给我一些提示吗?或者,如果这种方式更有效,请继续向我解释为什么它变成循环。

I've heard about Debounce and rxjs/rs but I'm not familiar with them, could you give me some tips to do the same with that? Or if this way is more efficient go ahead and explain to me why it becomes to a loop.

目标是当它加入if并推送页面时,停止计时器。

The goal is when it joins the if and push the page, stop the timer.

推荐答案

更好地使用observables

Better use observables

this.sub = Observable.interval(10000)
    .subscribe((val) => { console.log('called'); }

停止使用

this.sub.unsubscribe();

确保导入 interval

import 'rxjs/add/observable/interval';

这篇关于每10秒调用一次函数Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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