使用 async 管道来订阅行为主题并在模板中显示其值。
在组件的 ngOnInit 方法中创建一个行为主题:
import { Component, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-my-component',
template: `
Value: {{ value$ | async }}
`,
})
export class MyComponent implements OnInit {
value$ = new BehaviorSubject(0);
ngOnInit() {
setInterval(() => {
const currentValue = this.value$.getValue();
this.value$.next(currentValue + 1);
}, 1000);
}
}
在 template 中,使用 async 管道订阅 value$ 行为主题并显示其值。
在组件的 ngOnInit 方法中可以更改值。
value$ 行为主题在组件销毁时自动取消订阅。
这样,每次更改值时,模板将自动更新该值。