这样做的方法是:
import { map, timer } from 'rxjs';
@Component({
...
})
export class HeroComponent {
words = ['marco', 'polo'];
word = timer(0, 4000).pipe(
map((num) => {
const index = num % this.words.length;
const word = this.words[index];
console.log(word);
return word;
})
);
}
然后在html中使用异步管道:
<p>{{ word | async }}</p>
示例:
https://stackblitz.com/edit/angular-ivy-7xbuft?file=src/app/app.component.ts
timer
从RxJS以递增的顺序(0、1、2、3,…)发出整数从第一个参数(0ms)开始,然后在第二个参数(4000ms)给定的间隔内进行一次。
pipe
让我们在返回之前对任何发出的值执行一系列操作。
map
获取发出的值并返回不同的值,在本例中,我们使用整数计算数组的索引,然后在该索引处返回单词。
这个
async
管道将订阅可观察到的,并在组件被销毁时取消订阅,从而停止执行。取消订阅对于防止内存泄漏很重要。