Angular8中回调函数内改变数据但视图不能实时更新
解决方法就是通过依赖注入给组件来引入一个ChangeDetectorRef,并标注组建树目录,告诉angular此处需要监测,具体方法见代码:
@Component({
template: '{{num}}',
changeDetection: ChangeDetectionStrategy.OnPush
})
class Example {
constructor(private cdf: ChangeDetectorRef) {} // 依赖注入ChangeDetectorRef
@Input() addNumStream:Observable<any>;
num = 0;
ngOnInit() {
this.addNumStream.subscribe(() => {
this.num++;
this.cdf.markForCheck(); // 进行标注
this.cdf.detectChanges(); // 要多加一行这个 执行一次变化检测
})
}
}
- 上一篇 »JavaScript中的回调函数,callback
- 下一篇 »python中进程池和回调函数