离子2弹出处理程序函数不更新变量

时间:2017-05-09 13:50:03

标签: angular ionic-framework ionic2

我正在尝试更新变量“OK”点击弹出窗口,但有些我怎么也无法更新变量。在控制台中,它显示更新的值,而不是在视图中更新。

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;变量未在view / html

中更新

1 个答案:

答案 0 :(得分:0)

您需要使用NgZoneChangeDetectorRef

通知Angular Change Detection更新视图
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