Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why observable.subscribe works only from constructor

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.

like image 508
BeeBee8 Avatar asked Nov 07 '22 03:11

BeeBee8


1 Answers

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;
        });
    });
}
like image 66
theriddle2 Avatar answered Nov 14 '22 21:11

theriddle2