Bar*_*urg 8 angular2-changedetection angular
我有一个场景,其中有两个组件并排放置,ComponentA 和 ComponentB。它们都使用服务 Service。
ComponentB 包含一个按钮,它将使 Service 中的一个属性 Service.counter 增加 1。
ComponentA 呈现 Service.counter 的值。
但是,当我使用 ChangeDetectionStrategy.OnPush 时,无论我尝试什么,我都无法更新 ComponentA 中的值,即使从我尝试过的根组件中也是如此:
this.cdr.markForCheck();
this.cdr.detectChanges();
this.ar.tick();
this.zone.run(() => {});
Run Code Online (Sandbox Code Playgroud)
无需对 ComponentA 进行更改,如何确保它始终显示正确的值?
(真实世界的情况是,有很多像ComponentA的组件都呈现翻译值,并且当所选语言更改时,我需要所有这些翻译的值相应地更新。我不想将侦听器建立在每个单个组件中从那里调用detectChanges)
但是,当我使用 ChangeDetectionStrategy.OnPush 时,无论我尝试什么,我都无法更新 ComponentA 中的值,即使从我尝试过的根组件中也是如此:
一个组件有一个关联的视图。视图引用 DOM 并且是我们想要更新的内容。当您使用OnPush组件的视图时,如果组件的状态在外部发生变化,则需要将其标记为脏视图。
当你说even from the root component这意味着你试图将错误的视图标记为脏的。如果您想查看更改,ComponentA则需要将该组件视图标记为脏。
像这样的东西。
@Component({...})
public class ComponentA implements OnInit {
public count; // rendered in the view
public constructor(private _change: ChangeDetectorRef,
private _service: MyService) {
}
public onInit() {
this._service.getCounter().subscribe(value=> {
this.count = value; // will not update the view.
this._change.markForCheck(); // tell Angular it's dirty
});
}
}
Run Code Online (Sandbox Code Playgroud)
所以上面的getCounter()方法在 99% 的情况下都可以工作,但是如果这些方法返回一个在 Angular 范围之外执行的 observable,并且你必须明确地这样做,因为异步操作是自动分区的,那么你必须使用该zone.run()方法。否则,即使您将视图标记为脏。Angular 不会检查是否有任何视图需要更新。除非您使用非 Angular 事件或已明确在 Angular 之外运行,否则这不应发生。
另一种方法是使用async管道,这是更简单的方法。
@Component({
template: `<span>{{count$ | async}}</span>`
})
public class ComponentA implement OnInit {
public count$: Observable<number>;
public constructor(private _service: MyService) {
}
public onInit() {
this.count$ = this._service.getCounter();
}
}
Run Code Online (Sandbox Code Playgroud)
该async管道采用的是参考ChangeDetectorRef也将迎来视图脏了你。因此,它使您免于大量样板代码。
现实世界的场景是,有很多组件,如 ComponentA,都渲染翻译值,当所选语言发生变化时,我需要所有这些翻译值进行相应更新。我不想在每个单独的组件中构建一个监听器并从那里调用 detectChanges
那么你最好的选择是使用async管道并使你的组件具有反应性。
如果我们谈论的是大规模的东西并影响很多组件,那么这个根组件可能应该将值传递给组件作为 an @Input(),这也将触发它们被渲染。虽然这会在所有组件之间创建耦合,但它表示您不必担心更新视图。
| 归档时间: |
|
| 查看次数: |
2950 次 |
| 最近记录: |