In my ionic2 app, I tried to use a Cordova plugin that's not included in Ionic Native. I referred to the article wrote by Josh Morony here: https://www.joshmorony.com/using-cordova-plugins-in-ionic-2-with-ionic-native/. Everything works fine (the code is compiled, executed with no problem).
Since this plugin is not supported by Ionic Native, no promise and observable, and it will take some time to respond. This plugin did return value. I tried to assign the returned value from plugin to my view and it fails (error msg: TypeError: null is not an object (evaluating 'this.name=t')).
PS: If I just put response in alert, alert(response), it shows the returned value correctly.
Below is my code, can anyone here please help me? Thank you very much :-)
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Platform } from 'ionic-angular';
declare var airwatch;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
name: string = null;
constructor(public navCtrl: NavController, platform: Platform) {
// code starts here
platform.ready().then(() => {
(<any>window).plugins.airwatch.username(function(response){
alert(response);// this alert works! it will correctly show the response in text mode (the response is text)
this.name = response; // the line failed, it said: cannot insert null to this.name but I thought the response is text and it works when I use alert or console.log
}, function(error){
this.name = error;
});
});
}
}
I also tried to place the code in ionViewDidLoad() {}, but it still didn't work. Same error message: TypeError: null is not an object (evaluating 'this.name=t')
I tried to NgZone, but it didn't work.
Is it because the returned value is not in angular "scope"?
You need to keep a reference to 'this' as the second 'this', the one in the callback, is relative to the callback.
so just add
let self = this;
before calling the plugin, then in the callback you can use your newly created 'self' variable. Your code will looks like
let self = this;
(<any>window).plugins.airwatch.username(function(response){
alert(response);// this alert works! it will correctly show the response in text mode (the response is text).
this.name = response; // the line failed, it said: cannot insert null to self.name but I thought the response is text and it works when I use alert or console.log
}, function(error){
self.name = error;
});