Angular2 FileTransfer.upload响应未在视图中更新

时间:2016-02-24 08:03:45

标签: 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.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

);
}

1 个答案:

答案 0 :(得分:2)

引用它们时需要绑定函数:

ft.upload(imageURI, encodeURI("https://myserver"),
          this.win.bind(this), this.fail.bind(this), file);

否则,您在这些函数中使用的this将不会对应于组件本身的实例。因此,在this.res方法中使用win,这样就无法更新组件的res属性...

另一点。为什么要手动实例化NgZone而不是使用注入的?{/ p>

constructor(private zone:NgZone) {
  this.res = [];
}

win(r) {
  this.zone.run(() => {
    (...)
  });
}