问题
While working on Ionic 3 app I have faced problem that when you subscribe to observable from service in ngOnInit and update a local variable into it, it does not update the view.
For e.g
HTML template
<p>{{myVariable}}</p>
constructor(myService: MyService) {
}
ngOnInit() {
this.myService.myObservable.subscribe((data) => {
this.myVariable = data;
});
}
But when you do same thing from constructor, it works.
contructor(myService: MyService) {
this.myService.myObservable.subscribe((data) => {
this.myVariable = data;
});
}
Its an Ionic 3 app. It contains different Ion Tabs. The problem is that the view is not updated automatically when you subscribe in ngOnInit. You have switch between tabs for it to work. But when you subscribe in constructor it works without needing to switch tab.
Any idea why this is happening. Any hints will be appreciated. Thanks.
回答1:
It has to do with Angular change detection, for more info about this, read: Angular Change detection.
You should use Angular ngZone service to solve this, it will update the view.
import { Component, NgZone } from "@angular/core";
constructor(
private ngZone: NgZone
...
){ }
...
ngOnInit() {
this.myService.myObservable.subscribe((data) => {
this.ngZone.run(() => {
this.myVariable = data;
});
});
}
回答2:
You do not clarify what kind of observable you have (e.g. 'cold', 'hot', Subject, BehaviorSubject, an HttpClient observable, etc.). If it is an observable that you have created yourself, it may well be that its value changed before you subscribe to it in the ngOnInit method and therefore depending on the type of observable the value is lost. Since the service that created the observable is injected in the constructor, the constructor gets earlier access to whatever value may be emitted by the service.
If you are constructing the observable yourself, consider using a BehaviorSubject:
What is the difference between Subject and BehaviorSubject?
回答3:
use private myService
contructor(private myService: MyService) {
this.myService.myObservable.subscribe((data) => {
this.myVariable = data;
});
}
来源:https://stackoverflow.com/questions/51876486/why-observable-subscribe-works-only-from-constructor