我正在使用ionic2 / angular2应用程序开发移动应用程序。我们必须调用另一个外部API来显示一个对话框。从另一个控件返回到我的应用程序后, AlertController 范围无效。
import {AlertController, Events } from 'ionic-angular';
export class BalanceInquiryPage {
constructor(){
public alertCtrl: AlertController,
public events: Events,
}
public balanceDetials(formdata): void {
//fetch the device details from sqlite storage
this.databaseService.getDeviceDetails().then((result) => {
this.commonServices.getGeoLocation(this.deviceObj);
setTimeout(() => {
let geodevice = this.shareService.getDeviceDetails();
let balanceenq = JSON.stringify({"mobileNumber":"9199403562", "expDate":"","cardDigits":""});
if (window.npciLib){
window.npciLib.balanceenq(balanceenq, function (data) {
let dataobj = JSON.parse(data);
if(dataobj.resp.result == 'SUCCESS'){
//this.events.publish('alert:presented', 'Success', 'Balance Enquiry Success.', MyaccountPage);
let alert = this.alertCtrl.create({
title: "Success",
subTitle: "balance",
buttons: [
{
text: 'Ok',
handler: () => {
}
}
]
});
alert.present();
}
else{
//this.events.publish('alert:presented', 'Fail', 'There was an error in balance enquiry.', 'samePage');
}
}, function (error) {
console.log('error block-'+error);
});
}
}, 1000);
}, (error) => {
console.log('Error', error.err);
});
}
}
我收到以下错误:
未捕获的TypeError:无法读取null的属性'alertCtrl'
答案 0 :(得分:5)
在这里使用箭头功能
window.npciLib.balanceenq(balanceenq, function (data) {
像
window.npciLib.balanceenq(balanceenq, (data) => {
这种方式this
将被引用到您的组件实例
答案 1 :(得分:0)
在Angular 2中使用箭头功能;它将解决范围问题。
import {AlertController, Events } from 'ionic-angular';
export class BalanceInquiryPage {
constructor(){
public alertCtrl: AlertController,
public events: Events,
}
public balanceDetials(formdata): void {
//fetch the device details from sqlite storage
this.databaseService.getDeviceDetails().then((result) => {
this.commonServices.getGeoLocation(this.deviceObj);
setTimeout(() => {
let geodevice = this.shareService.getDeviceDetails();
let balanceenq = JSON.stringify({"mobileNumber":"9199403562",
"expDate":"","cardDigits":""});
if (window.npciLib){
window.npciLib.balanceenq(balanceenq ,(data) => {
let dataobj = JSON.parse(data);
if(dataobj.resp.result == 'SUCCESS'){
//this.events.publish('alert:presented', 'Success',
'Balance Enquiry Success.', MyaccountPage);
let alert = this.alertCtrl.create({
title: "Success",
subTitle: "balance",
buttons: [
{
text: 'Ok',
handler: () => {
}
}
]
});
alert.present();
}
else{
//this.events.publish('alert:presented', 'Fail', 'There
was an error in balance enquiry.', 'samePage');
}
}, function (error) {
console.log('error block-'+error);
});
}
}, 1000);
}, (error) => {
console.log('Error', error.err);
});
}
}