【发布时间】:2017-08-15 18:15:19
【问题描述】:
假设我的 service.ts 中有一个 function noificationHandler(),它在 Angular 的上下文之外。
noificationHandler() 被第三方调用,noificationHandler() 基本上是使用一个数组并将该数组发送给订阅了他的服务的组件。
service.ts
public mySubject: Subject<any> = new Subject();
public myObservable = this.mySubject.asObservable();
constructor() {
this.registry.subscribe("notification.msg",this.noificationHandler.bind(this));
}
noificationHandler(data) {
this.publishUpdate(data)
}
publishUpdate(data) {
this.mySubject.next(data);
}
component.ts
constructor(private service: myService) {
this.service.myObservable.subscribe(list => {
this.list = list;
});
}
^^^ 此时模板没有用新数据更新
由于"notification.msg" 在 angular 的区域之外,因此 angular
调用此 event("notification.msg") 时不会运行更改检测。
现在有两种调用变更检测的方法。
1) 通过将 noificationHandler() 包裹在 angular 的 zone.run() 中
this.registry.subscribe("a2mevent.notification.msg", this.ngZone.run(() => this.noificationHandler.bind(this)));
2) 通过单独要求组件检测变化
constructor(private service: myService, private ref: ChangeDetectorRef) {
this.service.myObservable.subscribe(list => {
this.list = list;
this.ref.detectChanges(); // <==== manually invoking change detection
});
}
这两个选项都有效! 而我的组件结构如下
A --> root component
B
C
D // my component is here (4 levels of nesting)
问题 -
1) detectChanges() 会仅检测其自身组件的更改,还是也会对子组件运行更改检测?
2) zone.run() 会触发从根到叶所有组件的变化检测吗?
在 zone.run() 和 detectChanges() 中,我很好奇 性能 哪个更好?
【问题讨论】:
标签: javascript angular angular2-changedetection