When I was creating my beacon-starter application that I blogged about here, I came across a problem that I had not encountered before in any of my Ionic apps.
In my home.ts component I subscribe to an event which is fired when beacons are discovered. My code was (originally):
listenToBeaconEvents() {
this.events.subscribe(‘didRangeBeaconsInRegion’, (data) => {this.beacons = [];
let beaconList = data.beacons;
beaconList.forEach((beacon) => {
let beaconObject = new BeaconModel(beacon);
this.beacons.push(beaconObject);
});});
}
What I expected to happen here was that my beacons array (which was represented on my template using *ngFor in the standard way) would be refreshed with the values from my beacon objects. Unfortunately, nothing was displayed on screen despite the objects being created successfully.
What I discovered was that for the first time (for me) I needed to look at Angular Zone Change Detection which you can read about here. In my case I needed to make three small changes to my component to get it to work:
first, import the NgZone module:
import { NgZone } from “@angular/core“;
second, create an NgZone:
this.zone = new NgZone({ enableLongStackTrace: false });
third, wrap my update code inside of this.zone.run() :
listenToBeaconEvents() {
this.events.subscribe(‘didRangeBeaconsInRegion’, (data) => {
this.zone.run(() => {this.beacons = [];
let beaconList = data.beacons;
beaconList.forEach((beacon) => {
let beaconObject = new BeaconModel(beacon);
this.beacons.push(beaconObject);
});});
});
}
Once these changes were in place the model changes were detected successfully and the UI updated.
I need to read up on Angular Zones and Change Detection I think because this was a new problem for me. Hopefully, this may help someone else who has a similar issue.
Thank you! It worked!
Just what I needed. Thank you.
Thank you!!!
Marvelous! Many Thanks!
Didn’t work for me until i put it into constructor:
constructor( private zone:NgZone ){
}
Merci 👍👌
Thanks a lot, this helped. I didn’t have to put the zone in the constructor as @Eldar did. Things worked for me by instantiating my zone in the constructor though I did not have to pass one in through dependency injection.
Oops!!! It also works by adding this line.
Observable.interval().subscribe();
Big Thanks
Save my day..You are champ
Thanks. I love u men
Thanks Richard! While I’m not sure if it way your script or not that helped, I also did this update to my app in combination with yours and now my app is actually working as expected – in all browers and devices. Thanks!
Thanks Richard! While I’m not sure if it way your script or not that helped, I also did this update to my app in combination with yours and now my app is actually working as expected – in all browers and devices. Thanks!
https://stackoverflow.com/a/35018352/1190051
Thank you boss, fixed my shit
You saved my life, I was stucked since yesterday!
cheers mate! i was stuck for hours!