javascript - 在cordova相机插件的success方法中调用angluar2方法

标签 javascript android angular cordova android-camera

我已成功将 cordova 插件集成到我的 angular2 项目中。 我调用“takePicture”方法,该方法成功调用 native 相机。

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

关于javascript - 在cordova相机插件的success方法中调用angluar2方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674461/

相关文章:

javascript - 目录样式 URL 上的 PHP "Go to Parent Page"按钮

安卓错误 : Error: No resource found that matches the given name

javascript - 如何创建一个 Angular 分量的独立实例

javascript - 如何使用 async/await 返回 Ajax 结果?

javascript - Javascript 中的 isPrototypeOf

android - 连接用户和 Firebase 数据库

javascript - 在线时影响非 GET 请求的服务 worker - @angular/pwa

node.js - 无法解析 'buffer' 中的 'C:\Portal\\node_modules\string_decoder\node_modules\safe-buffer'

javascript - 避免对 HTML DOM 的所有内容进行 GET

android - 如何在 Eclipse 中安装 m2e-android-plugin?