Search code examples
angularandroid-cameranativescriptnativescript-angular

Nativescript Angular Cannot assign image to property after taking picture


I'm using nativescript-camera to capture image in my android apps but i always getting TypeError: Cannot set property 'imageSource' of undefined. I'm following the guide here , all my camera code seems correct and i not sure where i did wrong.

export class SocialRegistrationComponent implements OnInit {

    imageSource: ImageSource;

    constructor() {}

    ngOnInit() {
    }

    capturePicture() {

        const options = {
        saveToGallery: false,
        allowsEditing: false,
        format: 'png'
        };

        camera.requestPermissions().then(
            function success() {
                camera.takePicture(options)
                .then((capturedImageAsset) => {

                    let imageSource = new imageSourceModule.ImageSource;

                    imageSource.fromAsset(capturedImageAsset)
                    .then((capturedImageSource: ImageSource) => {

                        console.log(capturedImageSource); // Display correctly
                        this.imageSource = capturedImageSource; // Error here, this.imageSource undefined
                    });
                }).catch((err) => {
                    console.log('Error -> ' + err.message);
                });
            }, 
            function failure() {
                // failed
            }
        );

    }

}

Solution

  • The context (this) will not be pointing to Angular component inside success function. You have to use arrow function or retain context in local variable.

    success() => {
      // Using arrow function retains the context
      .... 
    }