>我正在尝试在弹出窗口的"确定"单击时更新变量,但有些我无法更新变量。在控制台中,它显示更新的值,而未在视图中更新。
this.barcodeScanner.scan().then((barcodeData) => {
let alert = this.alertCtrl.create({
title: 'Barcode scanned Successfully!',
subTitle: ''+barcodeData.text,
buttons: [{
text: 'OK',
handler: () => {
this.showForm = true;
this.memberVo["barcodeId"] = barcodeData.text;
}
}]
});
alert.present();
}, (err) => {
// An error occurred
console.log('barcode err--',err);
let alert = this.alertCtrl.create({
title: 'Barcode scan Failed!',
subTitle: ''+err,
buttons: ['OK']
});
alert.present();
});
这里this.showForm = true;
变量没有在视图/html 中更新
您需要
使用 NgZone
或 ChangeDetectorRef
通知角度变化检测更新视图
constructor(private zone: NgZone) {}
然后做这样的事情
this.zone.run(() => {
this.barcodeScanner.scan().then((barcodeData) => {
let alert = this.alertCtrl.create({
title: 'Barcode scanned Successfully!',
subTitle: ''+barcodeData.text,
buttons: [{
text: 'OK',
handler: () => {
this.showForm = true;
this.memberVo["barcodeId"] = barcodeData.text;
}
}]
});
alert.present();
}, (err) => {
// An error occurred
console.log('barcode err--',err);
let alert = this.alertCtrl.create({
title: 'Barcode scan Failed!',
subTitle: ''+err,
buttons: ['OK']
});
alert.present();
});
});
或使用ChangeDetectorRef
constructor(private cdRef: ChangeDetectorRef) {}
然后
this.barcodeScanner.scan().then((barcodeData) => {
let alert = this.alertCtrl.create({
title: 'Barcode scanned Successfully!',
subTitle: ''+barcodeData.text,
buttons: [{
text: 'OK',
handler: () => {
this.showForm = true;
this.memberVo["barcodeId"] = barcodeData.text;
this.cdRef.detectChanges(); // this one
}
}]
});
alert.present();
}, (err) => {
// An error occurred
console.log('barcode err--',err);
let alert = this.alertCtrl.create({
title: 'Barcode scan Failed!',
subTitle: ''+err,
buttons: ['OK']
});
alert.present();
});
文档:
https://angular.io/docs/ts/latest/api/core/index/ChangeDetectorRef-class.html
https://angular.io/docs/ts/latest/api/core/index/NgZone-class.html