Ionic UI not updating after change to model

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.

 

 

 

 

 

 

 

 

3 thoughts on “Ionic UI not updating after change to model

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s