Typescript 角度2+;离子型2+;条形码扫描仪DOM未在绑定更改时更新

Typescript 角度2+;离子型2+;条形码扫描仪DOM未在绑定更改时更新,typescript,angular,cordova-plugins,ionic2,Typescript,Angular,Cordova Plugins,Ionic2,我一直在尝试从成功函数中访问绑定。这是我的代码: import {Page, Platform, Modal, NavController, NavParams, ViewController} from 'ionic-angular'; import {Component, Input} from 'angular2/core'; @Page({ templateUrl: 'build/pages/addModal/addModal.html', directives: [] })

我一直在尝试从成功函数中访问绑定。这是我的代码:

import {Page, Platform, Modal, NavController, NavParams, ViewController} from 'ionic-angular';
import {Component, Input} from 'angular2/core';

@Page({
  templateUrl: 'build/pages/addModal/addModal.html',
  directives: []
})

export class addModal {
  public barcode: String = '';

  static get parameters() {
    return [[ViewController], [Platform]];
  }

  constructor(public _viewCtrl: ViewController, _platform: Platform){
    var category = "Grocery";
    this.barcode = '';

    _platform.ready().then(() => {

      this.openScanner();

    });
  }

  openScanner() {
    cordova.plugins.barcodeScanner.scan(
        (result) => {
          console.log('DEBUG || Barcode scanned: ' + result.text);
          this.barcode = result.text;
        }, 
        (error) => {
            alert("Scanning failed: " + error);
        }
      );
  }

  close() {
    this._viewCtrl.dismiss();
  }
}
扫描仪扫描后,应将变量“条形码”更新为扫描的条形码。我知道扫描仪正在工作,因为它成功地记录了输出

问题是DOM根本没有更新。HTML模板是:

    <ion-item>
      <ion-label fixed>Barcode</ion-label>
      <ion-input type="text" placeholder="eg. 5058937528594" [value]="barcode" (input)="barcode=$event.target.value"></ion-input>
      <button (click)="openScanner()" outline item-right>
        <ion-icon name="qr-scanner"></ion-icon>
      </button>
    </ion-item>
没有任何成功。没有显示错误消息,我相信通过在safari dev控制台中进行调试,“this”被正确引用并可访问(使用不在浏览器中的设备。我知道cordova不能在PC浏览器上工作!)

Edit:So调用console.log(this.barcode)后;紧接着this.barcode=result.text;我发现它没有更新变量?为什么会这样?


编辑2:现在它正在更新。如果我将其包装在超时函数中,它不会更新,因此我猜测它不会从成功函数中更新原始变量?

确保赋值在Angulars区域运行:

import {Component, Input} from 'angular2/core';

...

constructor(public _viewCtrl: ViewController, _platform: Platform, private zone:NgZone){ ... }

...
this.zone.run(() => this.barcode = result.text;);
另见


尝试使用分区。您可以在此处找到有关此问题的讨论

链接-不鼓励提出问题。请至少在答案中直接添加最相关的内容。我正在使用此技术,但我不禁要问,Angular是否自动执行此操作?为什么我需要执行此操作?我的意思是一半的地方它工作,一半的地方它不工作。我应该用这段代码包装视图中需要反映的每个任务吗?Angular使用zone.js修补异步调用,如
setTimeout
addEventListener
,以了解何时发生“事情”,并在事后运行更改检测。如果您与运行在Angulars zone之外的代码进行交互(例如,传递回调),因为代码在Angulars应用程序之外初始化,或者因为它使用zone.js未涵盖的异步API,那么Angular在发生“某些事情”时不会收到通知,也不会运行更改检测。使用
zone.run()
可以将执行“强制”回Angulars区域,以执行更改检测。
setTimeout(() => this.barcode = result.text, 1);
import {Component, Input} from 'angular2/core';

...

constructor(public _viewCtrl: ViewController, _platform: Platform, private zone:NgZone){ ... }

...
this.zone.run(() => this.barcode = result.text;);