在Angular 2中,要实现每隔10秒调用一个函数可以通过以下步骤:
interval
和take
操作符,以及Subscription
类和所需的其他依赖项:import { interval, Subscription } from 'rxjs';
import { take } from 'rxjs/operators';
private subscription: Subscription;
private counter: number = 0;
ngOnInit()
中,使用interval
和take
操作符创建一个可观察对象,设置每隔10秒触发一次,并使用subscribe()
方法订阅该可观察对象:ngOnInit() {
this.subscription = interval(10000).pipe(take(Infinity)).subscribe(() => {
this.myFunction();
});
}
其中,myFunction()
是你想要每隔10秒调用的函数。
ngOnDestroy()
中,取消订阅以避免内存泄漏:ngOnDestroy() {
this.subscription.unsubscribe();
}
完整的示例代码如下所示:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { interval, Subscription } from 'rxjs';
import { take } from 'rxjs/operators';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit, OnDestroy {
private subscription: Subscription;
private counter: number = 0;
ngOnInit() {
this.subscription = interval(10000).pipe(take(Infinity)).subscribe(() => {
this.myFunction();
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
myFunction() {
this.counter++;
// 在这里编写你想要每隔10秒调用的代码逻辑
console.log('Function called every 10 seconds');
console.log('Counter: ' + this.counter);
}
}
这样,在Angular 2中,每隔10秒就会调用一次myFunction()
函数。你可以在myFunction()
中编写你需要执行的任何代码逻辑。