Angular 无法将Cordova插件返回值分配给Ionic2中的视图
在我的ionic2应用程序中,我尝试使用Ionic Native中未包含的Cordova插件。我在这里引用了Josh Morony写的文章:。一切都很好,代码编译、执行都没有问题 由于该插件不受Ionic Native支持,因此没有承诺和可观察性,并且需要一些时间才能做出响应。这个插件确实返回了值。我试图将插件返回的值分配给我的视图,但失败了错误消息:TypeError:null不是计算“this.name=t”的对象 PS:如果我只是把response放在alert,alertresponse中,它会正确地显示返回的值 下面是我的密码,这里有人能帮我吗?多谢各位:-Angular 无法将Cordova插件返回值分配给Ionic2中的视图,angular,ionic2,cordova-plugins,airwatch,Angular,Ionic2,Cordova Plugins,Airwatch,在我的ionic2应用程序中,我尝试使用Ionic Native中未包含的Cordova插件。我在这里引用了Josh Morony写的文章:。一切都很好,代码编译、执行都没有问题 由于该插件不受Ionic Native支持,因此没有承诺和可观察性,并且需要一些时间才能做出响应。这个插件确实返回了值。我试图将插件返回的值分配给我的视图,但失败了错误消息:TypeError:null不是计算“this.name=t”的对象 PS:如果我只是把response放在alert,alertresponse
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;
});
});
}
}
我还试图将代码放在ionViewDidLoad{}中,但仍然无法工作。相同的错误消息:TypeError:null不是计算“this.name=t”的对象
我试着打开分区,但没用
是因为返回值不在角度范围内吗?您需要保留对“this”的引用,因为回调中的第二个“this”是相对于回调的 所以只要加上
let self = this;
在调用插件之前,您可以在回调中使用新创建的“self”变量。您的代码看起来像
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;
});
可能是因为视图还没有准备好吗?非常感谢John:-