簡體   English   中英

回調中的訪問類屬性

[英]Access Class properties inside callback

我正在使用此插件:帶有Ionic 3的https://github.com/blinkmobile/cordova-plugin-sketch

我的最后一個重要步驟是使結果超出回調函數的范圍,以便進一步使用它。

這是我的代碼:

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

錯誤:未被捕獲的TypeError:無法讀取未定義的屬性'anhangArray'

您的問題是window.navigator.sketch.getSketch() 雖然window.navigator.sketch.getSketch會觸發您的回調this.onSuccess ,但這會更改回調的范圍。 要解決此問題,您可以更改實現,如下所示。

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

您也可以通過這種方式解決:

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

.bind(this)將范圍傳遞給調用者之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM