angular - Angular - AfterViewInit 发出新值时,异步管道不更新视图
问题描述
我有一个简单的组件,其中包含一个BehaviorSubject
. 在我的模板中,我使用async
管道更新视图并从我的BehaviorSubject
.
当值从OnInit
生命周期钩子发出时,async
管道会使用正确的值更新视图。但是当我尝试从中发出一个值时AfterViewInit
,async
管道不会更新视图。
这是正确的行为吗?为什么async
管道不会更新第二个发出的值?
示例组件:
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent implements OnInit, AfterViewInit {
public test$ = new BehaviorSubject(0);
constructor(public cd: ChangeDetectorRef) {
// All three values are logged - 0, 100, 200
this.test$.subscribe(console.log);
}
ngOnInit() {
// View is updated with 100 value
this.test$.next(100);
}
ngAfterViewInit() {
// View is not updated, async pipe is not triggered
this.test$.next(200);
}
}
示例组件模板:
<h1>{{ test$ | async }}</h1>
解决方案
您正在使用OnPush
更改检测策略。您应该手动触发检查更改:
ngAfterViewInit() {
// View is not updated, async pipe is not triggered
this.test$.next(200);
this.cd.detectChanges();
}
ngOnInit
在检查视图之前调用。所以100
会首先显示。
ngAfterViewInit
在对您的视图进行初始检查后调用。由于您使用的是OnPush
变更检测策略,因此它不会自动触发变更。
推荐阅读
- oauth - 来自AuthCode 的Snoowrap 请求者返回API 错误:invalid_grant - undefined
- python - Apache Airflow - Python 能力问题
- python - 如何使用 python 将维基百科页面拆分为段落?
- c++ - 构建系统 (C++)
- python - 为什么 Mypy 在 __init__ 中分配已在类主体中类型提示的属性时不给出输入错误?
- c++ - 如何检查c ++中的二维向量是否所有元素都为零?
- python - 给定数据框中项集的计数频率
- python - 我正在尝试加载一个 json 文件并得到一个错误
- ssl - 如何使用命令行轻松查看数字证书的详细信息
- java - 我对 Discord4Js MemberJoinEvent 有疑问