Angularjs Angular2 FileTransfer.upload响应未在视图中更新
下面是我的代码。sendFile函数工作正常,我可以在win函数中将结果记录到控制台,但变量不会在视图中更新Angularjs Angular2 FileTransfer.upload响应未在视图中更新,angularjs,angular,angular2-template,Angularjs,Angular,Angular2 Template,下面是我的代码。sendFile函数工作正常,我可以在win函数中将结果记录到控制台,但变量不会在视图中更新 constructor(zone:NgZone) { this.res = []; this.zone = new NgZone({enableLongStackTrace: false}); } win(r) { this.zone.run(() => { var temp = JSON.parse(r.response) temp = temp.P
constructor(zone:NgZone) {
this.res = [];
this.zone = new NgZone({enableLongStackTrace: false});
}
win(r) {
this.zone.run(() => {
var temp = JSON.parse(r.response)
temp = temp.ParsedResults[0].ParsedText
temp = temp.split('\n');
//this var is not updated in the view
this.res = temp
//this works fine
console.log(temp);
});
}
sendFile(imageURI){
var file = new FileUploadOptions();
file.fileKey="file";
file.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1)+'.jpg';
file.mimeType="text/plain";
var params = new Object();
params.apikey = "helloworld";
file.params = params;
var ft = new FileTransfer();
win
功能似乎无法访问this.res
ft.upload(imageURI, encodeURI("https://myserver"), this.win, this.fail, file);
}
scanImage(){
let options = {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,//DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG,
saveToPhotoAlbum: true,
allowEdit: true,
targetHeight: 1000,
correctOrientation: true
};
navigator.camera.getPicture(
(imageURI) => {
this.zone.run(() => {
img将在视图中更新
this.imageSrc = imageURI;
this.sendFile(imageURI);
});
},
(error) => {
console.log('error');
}, options
);
}
引用函数时需要绑定函数:
ft.upload(imageURI, encodeURI("https://myserver"),
this.win.bind(this), this.fail.bind(this), file);
否则,在这些函数中使用的this
将与组件本身的实例不对应。因此,以这种方式在win
方法中使用this.res
不会更新组件的res
属性
还有一点。为什么要手动实例化一个NgZone
,而不是使用注入的
constructor(private zone:NgZone) {
this.res = [];
}
win(r) {
this.zone.run(() => {
(...)
});
}
这非常有效。至于NgZone。。。没有理由。这是个新手犯的错误。从现在起我就这样做。