Changed variable not updating in view


#1

This is probably a newbie question but I’m very new to Ionic 2 and angular 2.

I need to check if Apple’s HealthKit is available on the user’s device. Why is the variable this.healthKitAvailable not updating in the view? The plugin is working and in the console I can see that the success callback fired.

Or do you guys suggest an entirely different approach?

Thanks :slight_smile:

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  healthKitAvailable: boolean = false;

  constructor(public navCtrl: NavController, public platform: Platform) {
    this.platform = platform;
  }

  ionViewWillEnter() {

    this.platform.ready().then((readySource) => {
      console.log('Platform ready from', readySource);

      // Check if user is running iOS
      if(this.platform.is('ios')) {
        console.log('Platform is iOS');

        // Check if HealthKit is available
        window.plugins.healthkit.available(
          () => {
            // Success
            console.log('HealthKit is available');
            this.healthKitAvailable = true;
          },
          () => {
            // Error
            console.log('HealthKit is NOT available');
          }
        );
      }
    });

  } // ionViewWillEnter()

}
<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

  <!-- HealthKit is not available -->
  <div *ngIf="!healthKitAvailable">
    HealthKit is not available
  </div>

  <!-- HealthKit is available -->
  <div *ngIf="healthKitAvailable">
    <p>HealthKit is available</p>
  </div>

</ion-content>
System information:

Cordova CLI: 6.3.1
Gulp version:  CLI version 1.2.1
Gulp local:
Ionic Framework Version: 2.0.0-rc.0
Ionic CLI Version: 2.1.0
Ionic App Lib Version: 2.1.0-beta.1
ios-deploy version: 1.9.0
ios-sim version: 5.0.8
OS: Mac OS X El Capitan
Node Version: v5.11.0
Xcode version: Xcode 8.0 Build version 8A218a

#2

Could it be that this in your callback is referring to the callback function, rather than your HomePage class?

Try to do let _this = this under your Platform ready from console log and then do _this.healthKitAvailable = true in your callback?


#3

Thank you very much for your help, I appreciate it very much!

Unfortunaltely it doesn’t work either. As far as I know this workaround isn’t required anymore when using () => {...} (and I can access this.healthKitAvailable in the callback without any problems).


#4

Did you figure it out? I’m having a similar problem.