pol52 pol52 - 2 years ago 106
TypeScript Question

CameraPreview takePicture() returns nothing

I have been trying to update an old app that had an old version of the camera-preview plugin, which still had the

setOnPictureTakenHandler
method that allowed me to return the url of the image.

The newer version of the plugin uses the
takePicture()
method in which I can define a function that will be called onSuccess and I defined that function to return the URL of the image taken. But I can't get that URL outside of the
onSuccess
function!

I have just been moving to typescript so I guess it's some sort of mistake managing variables. I am using a provider for the cameraPreview and I have created an envelope for the
takePicture()
method of the plugin. That envelope should return the URL to the controller in which I have injected the provider.

Here is the provider's envelope code:

url:string;
takePictures2() :string {
this.cameraPreview.takePicture(function(imgData){
this.url = "data:image/jpeg;base64" + imgData;
}).then();
return this.url;
};


Here is the controller code:

takePictures() {
let url : string = this.cameraPreview.takePictures2();
console.log(url);
}

Answer Source

I haven't tested the code below, but I would:

1) Promisify takePicture2. It wraps the takePicture method of the plugin and resolves the url when done:

takePictures2(): Promise<string> {
    return new Promise((resolve, reject) => {
        this.cameraPreview.takePicture(function(imgData) {
            resolve("data:image/jpeg;base64" + imgData);
        });
    };
};

2) make takePictures wait for takePictures2 to resolve:

takePictures() {
    let url : string;
    this.cameraPreview.takePictures2().then(url => {
        this.url = url;
        console.log(url);
    );
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download