本文介绍了Angular 6每X秒运行一次功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为
的函数 opensnack(text) { ... };
正在使用给定的文本输入打开角度材料小吃店./p>
我想做的是每10秒调用一次此函数.
我应该怎么做?
解决方案
使用 rxjs
interval
方法如下:
import { interval, Subscription } from 'rxjs';
subscription: Subscription;
...
//emit value in sequence every 10 second
const source = interval(10000);
const text = 'Your Text Here';
this.subscription = source.subscribe(val => this.opensnack(text));
...
ngOnDestroy() {
this.subscription.unsubscribe();
}
或者,您可以使用 setInterval
(可作为Window对象上的方法使用).因此,您无需导入任何内容即可使用它.
intervalId = setInterval(this.opensnack(text), 10000);
...
ngOnDestroy() {
clearInterval(this.intervalId);
}
这是一个 SAMPLE STACKBLITZ 供您参考.
I have a function called
opensnack(text) { ... };
which is opening an angular material snackbar with the given text input.
What I want to do is to call this function like every 10 seconds.
How should I do this?
解决方案
Use interval
from rxjs
Here's how:
import { interval, Subscription } from 'rxjs';
subscription: Subscription;
...
//emit value in sequence every 10 second
const source = interval(10000);
const text = 'Your Text Here';
this.subscription = source.subscribe(val => this.opensnack(text));
...
ngOnDestroy() {
this.subscription.unsubscribe();
}
Alternatively, you can use setInterval
which is available as method on the Window Object. So you don't need to import anything to use it.
intervalId = setInterval(this.opensnack(text), 10000);
...
ngOnDestroy() {
clearInterval(this.intervalId);
}
Here's a SAMPLE STACKBLITZ for your ref.
这篇关于Angular 6每X秒运行一次功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!