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.
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;
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With