简体   繁体   中英

Access Class properties inside callback

I'm using this plugin: https://github.com/blinkmobile/cordova-plugin-sketch with Ionic 3.

My last important step is to get the result outside the callback functions to work further with it.

This is my Code:

anhangArray: Array<{ name: string, value: string }>=[];



  takePhoto() {
  const options: CameraOptions = {
  quality: 100,
  destinationType: this.camera.DestinationType.FILE_URI,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
  correctOrientation: true,
  allowEdit: false,
}

this.camera.getPicture(options).then((imageData) => {

  // imageData is either a base64 encoded string or a file URI
  // If it's base64:
  //base64Image = 'data:image/jpeg;base64,' + imageData;
  //>>> FILE_URI
  this.getSketch(imageData);

}, (err) => {
  // Handle error
});
}

getSketch(src: string) {
window.navigator.sketch.getSketch(this.onSuccess, this.onFail, {
  destinationType: window.navigator.sketch.DestinationType.DATA_URL,
  encodingType: window.navigator.sketch.EncodingType.JPEG,
  inputType: window.navigator.sketch.InputType.FILE_URI,
  inputData: src
});
}

onSuccess(imageData) {
var _mythis = this;
if (imageData == null) { return; }

// do your thing here!
setTimeout(function () {
  if (imageData.indexOf("data:image") >= 0) {
  } else {
    imageData = "data:image/jpeg;base64," + imageData;
  }
  _mythis.anhangArray.push({ name: "anhang_" + parseInt(_mythis.user._kunnr), value: imageData });
  console.log(this.anhang);

}, 0);
}

Error: Uncaught TypeError: Cannot read property 'anhangArray' of undefined

Your problem is with window.navigator.sketch.getSketch() . While window.navigator.sketch.getSketch triggers your callback this.onSuccess , that changes scope of your the callback. To solve the issue, you can change the implementation like below.

getSketch(src: string) {
  window.navigator.sketch.getSketch(imageData => {
    this.onSuccess(imageData);
  }, error => {
    this.onFail(error);
  }, {
    destinationType: window.navigator.sketch.DestinationType.DATA_URL,
    encodingType: window.navigator.sketch.EncodingType.JPEG,
    inputType: window.navigator.sketch.InputType.FILE_URI,
    inputData: src
  });
}

you can solve in this way too:

 this.camera.getPicture(options).then((imageData) => { // imageData is either a base64 encoded string or a file URI // If it's base64: //base64Image = 'data:image/jpeg;base64,' + imageData; //>>> FILE_URI this.getSketch(imageData).bind(this); 

where .bind(this) pass the scope to your caller one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM