1

Below is my code. The sendFile function works fine and I can log the result to the console in the win function but the variable will not update in the view.

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();

the win function doesn't seem to have access to 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(() => {

the img updates in the view

      this.imageSrc = imageURI;
      this.sendFile(imageURI);
    });
  },

  (error) => {
    console.log('error');
  }, options

);
}

1 Answer 1

2

You need to bind function when referencing them:

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

Otherwise the this you use in these functions won't correspond to the instance of the component itself. So using this.res in the win method this way won't update the res property of the component...

Another point. Why do you instantiate an NgZone manually instead of using the injected one?

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

win(r) {
  this.zone.run(() => {
    (...)
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly. As for NgZone... no reason. New to angular so just a rookie mistake. I'll do it this way from now on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.