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

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

问题描述

我正在尝试创建一个 Timer 每 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);
}

我听说过 Debouncerxjs/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并push页面时,停止定时器.

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();

确保使用

import 'rxjs/add/observable/interval';

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

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