我想摆脱我应用程序中的区域。我正在考虑触发变更检测的几种方法:
this.changeDetectorRef.detectChanges()
/ ΘmarkDirty(this)
来手动触发更改检测。像这样:// extra side effect for observables:
readonly todos$ = this.todosService.getTodos().pipe(
tap(() => this.cdr.detectChanges()), // or `ΘmarkDirty(this)`
);
// or local state
toggle() {
this.isOpen = !this.isOpen;
this.cdr.detectChanges(); // or `ΘmarkDirty(this)`
}
<div [class.open]="isOpen">
<!-- AsyncPipe will invoke `ChangeDetectorRef#markForChanges()` which does nothing without zones -->
{{ todos$ | async | json }}
</div>
PushPipe
类似于this。该管道与内置AsyncPipe
非常相似,但是它调用ChangeDetectorRef#markForChanges
而不是ChangeDetectorRef#detectChanges
。考虑到即将发布的Ivy,我应该准备调用ΘmarkDirty(this)
,其中this
是对组件实例的引用。我可以通过注入的ViewRef
的{{1}}属性来引用组件实例,但是此属性是私有的,依赖私有API是一个坏主意。 在此组件模板中使用的管道中,有没有官方的方法可以获取组件实例引用?
context
类似于this。这种方法强制从父类继承一些基本功能。我希望人们在孩子课堂上改写ReactiveComponent
,而忘了打电话给ngOnDestroy$
。 我们无法强制适当地覆盖生命周期挂钩方法,对吧?
super.ngOnDestroy$()
装饰器,例如this。此方法在很大程度上依赖于@observed
前缀的函数和属性,这些函数和属性可能会发生变化。 而且,它感觉有点黑,因此在生产中使用它太冒险了,对吧?
您喜欢哪种方式?我是否缺少更好的选择?