Callback separated from the properties of the component

My journey with TypeScript and Angular 2 is just beginning.

I encountered an unusual issue with the Cordova Camera Plugin: it seems like callbacks are not properly connected to the rest of my component!

Below is a snippet of the code causing this problem:

result.component.ts

import {Component, OnInit} from "@angular/core";

@Component({
    moduleId: module.id,
    selector: 'app-result',
    templateUrl: 'result.component.html'
})
export class ResultComponent implements OnInit {
    pictureSource;
    destinationType;
    status = 0; //VALUE I WANT TO PRINT

    constructor() {
        this.pictureSource = navigator.camera.PictureSourceType;
        this.destinationType = navigator.camera.DestinationType;
    }

    ngOnInit(): void {

    }

    test() {
        console.log(this.status); //VALUE I PRINT
    }

    capturePicture() {
        let cameraOptions = {
            quality: 100,
            destinationType: this.destinationType.FILE_URI
        };
        navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFail, cameraOptions);
    }

    onCaptureSuccess(fileURI: string): void {
        console.log(this.status); //THROW ERROR
    }

    onCaptureFail(error: string): void {
        console.log('error', error);
    }
}

result.component.html

<div>
    <h1>Photo</h1>

    <button (click)="capturePicture()">PHOTO</button>
    <button (click)="test()">TEST</button>
</div>

Console output : https://i.sstatic.net/ZVhUL.png

Clicking on the TEST button works fine multiple times. However, after taking a photo using the PHOTO button and returning, the

'Cannot read property 'status' of null'
error occurs. After clicking the TEST button a few more times, the status value appears...

It appears that the callbacks for navigator.camera.getPicture are somehow isolated from the component. How can we understand this behavior?

Answer №1

I have never worked with Angular or Cordova before, but it seems like the issue here is related to the loss of context for this. The click handler in Angular respects the component's context, but when you pass a reference to a function in the line...

navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFail, cameraOptions);

...the getPicture function does not have access to your context. One way to fix this is by binding this:

navigator.camera.getPicture(this.onCaptureSuccess.bind(this), this.onCaptureFail, cameraOptions);

You could also use an arrow function, buffer this using a closure, or try other methods.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Retrieve the Root Path of a Project in a Cypress Test Script

Within my Nx workspace, I am currently testing an app using Cypress. The spec file I'm working with is nested within a subfolder structure like this: ${PROJECT_FOLDER}/apps/${APP_NAME}/cypress/e2e/${SOME_FOLDER}/test.cy.ts I need to find the absolut ...

The error message "trying to access markers property of undefined in the render function" occurred

I encountered this error while running my react-native component and need assistance. An error stating "undefined is not an object (evaluating 'this.state.markers.map')" occurred. This error appears in the following locations: c:\proje ...

Why does my body feel devoid whenever I submit a post request from the React JS frontend?

Angular js: export const addUser=( username, email )=> { return (dispatch) => { fetch("http://yourdomain.com/addUser", { method: "post", credentials: 'same-origin', mode: 'no-cors', ...

The consequences of jQuery Ajax Memory Leaks

After reading through several other posts on the topic, I have noticed a memory leak issue when making repeated ajax calls with jQuery (every 30 seconds in my case). Switching from using $get to $post helped reduce the size of the leak, but it still occurs ...

Tips on reducing image file size using JavaScript?

I've been attempting to reduce the size of an image using JavaScript, but I keep encountering a canvas error. Here's the code snippet I'm working with: var reader = new FileReader(); reader.readAsDataURL(fileItem._file); reader.onload = fun ...

Animating an element as the user scrolls down the page

I'm attempting to create a fading effect for a header on my website that should appear when the user scrolls past the initial section of the page. I currently have a div element with an opacity set to 0 and it transitions to an opacity of 1 as shown b ...

Ensure that the HTML input only accepts numbers and email addresses

Is there a way to restrict an HTML input field to only accept numbers and email IDs? <input id="input" type="text" /> ...

Trail of crumbs leading to pages displayed in a div container

My website is designed with only one page where all other pages are loaded within a div. I am looking to implement breadcrumbs to keep track of the pages loaded inside the div. However, the solutions I have found online only work for pages loaded in the en ...

Angular: Unable to modify the bound variable value in a directive from a transcluded child of another directive with a shared scope

I apologize if the title of this question seems complicated, but it's actually quite complex. Let me explain the situation: I have a directive with scope: false, transclude: true (Let's call this Directive1) Directive1's template refere ...

Critical bug discovered in fundamental Vue.js component by Internet Explorer

My Vue.js-powered application is performing flawlessly in all web browsers, except for one... Upon attempting to launch it on Internet Explorer, a frustrating error appears: An anticipated identifier in vue.min.js, line 6 character 4872 Locating the spe ...

Tips for decreasing the size of your Angular 7 production build

What are the best practices to minimize production build size? For production build, use the command ng build --prod To configure angular.json file, refer to the following links: https://i.stack.imgur.com/3LSxZ.jpg https://i.stack.imgur.com/yE0fL.jpg ...

Dynamically loading various compositions of EDGE

I'm currently working on developing a testing system for edge-animate compositions. The goal is to be able to load different compositions and verify that they are displaying correctly, as well as make changes to their customizable fields. I attempted ...

Stop Form Submission in Bootstrap 5

I require assistance with identifying the issue in the JavaScript code provided below. I am working with a Bootstrap 5 form where the submission is not being prevented if the fields are left blank or invalid. While the HTML/CSS validation works correctly f ...

Why is the Bootstrap tooltip flickering and not closing on mouseout? And why are duplicate entries not being triggered?

I'm facing some issues with the code I have here: Check it out The problems are as follows: Flickering - When hovering over the images slowly, there is noticeable flickering in the tooltip box rendering 2-3 times. This seems to be related to the cla ...

What is the reason for having two plugin declarations within the galleriffic.js file?

I am currently working on enhancing the functionality of galleriffic.js by implementing a feature that will update a <div> element with text content as images are being changed. However, I am facing some challenges understanding the code. What perpl ...

Converting array data into an HTML table using Javascript

I have a two-dimensional array containing strings, structured like this: [["Application1", "11106.exampleserver.com", "11109.exampleserver.com", "11102.exampleserver.com", "11105.exampleserver.com" "Database, AFPUOR(KNAJKLD)", "Database, UOQZRNJ(LKUJD)" ] ...

I am facing an issue with Firebase AngularFireAuth where I am unable to update a user's email even though the

I am facing an issue with my Angular Application where I cannot change the email of a logged-in authenticated user in Firebase. Fetching the email as an observable works fine: getUserEmail():Observable<string | null>{ return this.afAuth. ...

Mastering the art of counting down using a forEach loop in JavaScript

Trying to iterate through a list of objects, I can't index it, but can use forEach. My issue is I need to start from the last object and go to the first, but unsure how to achieve that with the forEach function. If I used a for loop, it would be like ...

Is it better to manually input a list of select options in the user interface or retrieve them dynamically from the database in case of future changes?

Imagine designing a user interface that allows users to choose their favorite Pokemon from options like Bulbasaur, Squirtle, and Charmander. Within the database, there is a lookup table containing all possible choices: pokemon --- id name 1 Bulbasaur 2 ...

What is the process for embedding a section of content from a different webpage into a separate division on my website?

Is there a way to pull content from one webpage and display it on another? Would using an Iframe be the best solution for this task? Thank you in advance for your assistance! ...