在 cordova 相机插件的成功方法中调用 angluar2 方法

call angluar2 method within the success method of the cordova camera plugin

我已经在我的 angular2 项目中成功集成了一个 cordova 插件。 我调用了"takePicture"方法成功调用了原生相机

public takePicture() {
    const srcType = navigator.camera.PictureSourceType.CAMERA;
    const options = this.setOptions(srcType);
    navigator.camera.getPicture(this.onSuccess, this.onFail,options);
  }

  public onSuccess(imageData) {
    this.capture('data:image/jpeg;base64,' + imageData); <-- this doesn't work here I guess

  }

  public onFail(message) {
    alert('Failed because: ' + message);
    console.log(message);
  }
.....

问题是当我拍照并调用 onSuccess 函数时,当我调用 this.capture(....) 时它会失败并出现以下错误:

core.es5.js:1084 ERROR TypeError: Cannot read property 'capture' of null

这意味着 angular 不知道方法 this.capture(..)。 有谁知道如何解决这个问题?

将实例方法作为回调传递时会丢失对象上下文,因此 this 的计算结果为 null

您可以通过将方法调用包装在一个函数中来轻松修复它:

navigator.camera.getPicture(
    (data) => this.onSuccess(data),
    (message) => this.onFail(message),
    options
);