Ionic 2 - accessing this from a plug-in callback

I’m no sure what I’m doing wrong here. I’m trying to get the version number of my app so I can present it on screen. I’m using the getAppVersion plug-in which works ok but I can’t pass the value returned back to an in scope variable.

My controller code is shown below. The platform ready code executes ok and the version number is written to the console. But the line that follows that errors with

Error in Success callbackId: AppVersion1774501 : TypeError: undefined is not an object (evaluating ‘this.appDetails.versionNo = version’)

It seems like I cannot get to this from within that callback. What do I need to do?

export class LoginCtrl {
  constructor(platform: Platform) {
  this.appDetails = {};

  platform.ready().then(() => {
   if (window.cordova) {
     cordova.getAppVersion(function(version) {
       console.log(version);
       this.appDetails.versionNo = version;
       console.log(this.appDetails.versionNo);
    });
   }
  });
}

Unlike $scope, what ‘this’ references changes based on the context in which it is called. Try this:

export class LoginCtrl {
  constructor(platform: Platform) {
  
  var me = this;
  this.appDetails = {};

  platform.ready().then(() => {
   if (window.cordova) {
    cordova.getAppVersion(function(version) {
    console.log(version);
    me.appDetails.versionNo = version;
    console.log(me.appDetails.versionNo);
   });
   }
  });
}

I’ve added a variable ‘me’ which will keep a consistent reference to the constructors scope.

6 Likes

Thank you thank you thank you! :grinning:

This helps me a lot. Thank you very much