可以使用RxJS中的Interval Observable来代替原生的setInterval函数,并使用takeUntil操作符来停止计时器。 示例代码如下:
import { Component, OnDestroy } from '@angular/core'; import { interval, Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-counter',
template: {{ counter }}
})
export class CounterComponent implements OnDestroy {
counter = 0;
private interval$ = interval(1000);
private stop$ = new Subject
start() { this.interval$ .pipe(takeUntil(this.stop$)) .subscribe(() => { this.counter++; }); }
stop() { this.stop$.next(); this.stop$.complete(); this.counter = 0; }
ngOnDestroy() { this.stop$.next(); this.stop$.complete(); } }
在上面的代码中,我们定义了一个Interval Observable来代替setInterval函数,并在start函数中使用takeUntil操作符来停止计时器。我们还定义了一个stop$Subject来控制计时器应停止,并在stop函数中调用了next和complete方法以确保计时器被完全停止。我们也实现了ngOnDestroy接口以在组件销毁时停止计时器并清零计数器。