使用Angular的“async”管道来触发变更检测。
示例代码:
import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs';
@Component({
selector: 'app-example',
template: `
{{ value$ | async }}
`
})
export class ExampleComponent implements OnInit {
value$ = of('Initial value');
ngOnInit() {
setInterval(() => {
this.value$ = of(Math.random().toFixed(2));
}, 2000);
}
setValue() {
this.value$ = of('New value');
}
}
在上面的示例中,我们使用RxJS的“of”操作符来创建一个可观察对象,并将其赋值给组件的属性“value$”。但是,“of”操作符不会触发Angular的变更检测,因此在组件中对“value$”赋值不会更新模板中的内容。
我们可以使用Angular的“async”管道来解决这个问题。将模板中的“value$”绑定到“async”管道上,它将自动订阅和取消订阅可观察对象,并触发变更检测。在组件中对“value$”进行赋值后,管道会自动更新模板中的内容。
因此,我们将模板中的“{{ value$ }}”改为“{{ value$ | async }}”就可以解决该问题。
上一篇:Angular|RxJS-浏览器在点击时取消了自动完成搜索请求
下一篇:Angular“formGroupexpectsaFormGroupinstance.Pleasepassonein.错误。