Say I have a function noificationHandler()
in my service.ts that is outside of angular's context.
noificationHandler()
is invoked by a third party and noificationHandler()
basically consumes an array and emits the array to components which have subscribed to his service.
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;
});
}
^^^ at this point the template is not updated with the new data
Since the "notification.msg"
is outside of angular's zone, angular
s change detection is not run when this event("notification.msg")
is invoked.
Now there are 2 ways to invoke change detection.
1) By wrapping the noificationHandler()
inside of angular's zone.run()
this.registry.subscribe("a2mevent.notification.msg", this.ngZone.run(() => this.noificationHandler.bind(this)));
2) By individually asking the component to detect changes
constructor(private service: myService, private ref: ChangeDetectorRef) {
this.service.myObservable.subscribe(list => {
this.list = list;
this.ref.detectChanges(); // <==== manually invoking change detection
});
}
Both the options work! And my component structure is as follows
A --> root component
B
C
D // my component is here (4 levels of nesting)
Questions -
1) Will detectChanges() detect changes only for its own components or will it also run change detection on child components?
2) will zone.run() trigger the change detection of all the components from the root till the leaf?
Among the zone.run() and detectChanges() I am curious as to which is better in performance?