关于Angular2中回调函数与数据绑定不能实时更新的问题

在angular2中调用扫描接口,现在可以将值正确添加到数组里,如下:


constructor() {
this.records = [];
}

barcodeScanner() {
var self = this;
cordova.plugins.barcodeScanner.scan(function (result) {
if (!result.cancelled) {
self.records.unshift(result);
alert(self.records.length);
}
}, function (error) {
alert("发生了一个错误:" + error);
});
}

但在页面中绑定的数据,无法实时更新。也就是回调函数中变化的值如何能实时更新到页面中,请多指教!

    *ngIf="records.length>0">
  • *ngFor="#record of records">{{record.format}} : {{record.text}}

答:回调函数跑出了Angular2的zone,所以需要注入ChangeDetector,显式地通知Angular2框架

进行更新,类似于Angular1.x中的apply()如下为正确处理后找码:

import {ChangeDetectorRef} from "angular2/core";

@Page({
templateUrl: 'build/pages/page1/page1.html',
})
export class Page1 {
constructor(ref: ChangeDetectorRef) {
this.ref = ref;
this.records = [];
}

barcodeScanner() {
var self = this;
cordova.plugins.barcodeScanner.scan(function (result) {
if (!result.cancelled) {
self.records.unshift(result)
;
self.ref.markForCheck();
self.ref.detectChanges();
}
}
, function (error) {
alert("发生了一个错误:" + error);
});
}
}
经过实践不知何故仅markForCheck依然不能刷新结果我在markForCheck后面加了detectChanges终于实现将扫描结果返回到页面上了


你可能感兴趣的:(angular2.0)