简体   繁体   中英

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

I've successfully integrated a cordova plugin within my angular2 project. I call the "takePicture" method which succesfully calls the native camera.

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

The problem is when I take a picture and I call the onSuccess function it will fail when I call this.capture(....) with the following error:

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

which means angular doesn't know the method this.capture(..). Does anyone know how to fix this?

You lose the object context when passing instance methods as callbacks, therefore this evaluates to null .

You can easily fix it by wrapping the method call in a function:

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

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