How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members in the callback function.

Below is the code snippet:

export class ConfirmBoxComponent extends DialogContentBase implements OnInit{
     constructor(public dialog: DialogRef, public myService : MyService) {
        super(dialog);
       
      }
      ngOnInit(): void {
        this.handleHardwareBackButton();
      }
     
      public onCancelAction(): void {
        console.log("Cancel confirmed", this.dialog)
        myService.closeDialog(); // closeDialog not accessible through arrow or callback functions
      }
    
  handleHardwareBackButton(){
   App.addListener('backButton',function(){
    this.onCancelAction() // unable to access onCancelMethod within callback
   })
  }

    }

I am receiving a "this.onCancelAction is not a method" error. I also attempted the following code but it did not resolve the issue:

handleHardwareBackButton(){
   App.addListener('backButton',function(){
    this.dialog.close({ actionConfirmed : false }); //this line does not execute and no errors are shown
   }.bind(this))
  }

Is there something I am missing? Could you please provide guidance on how to properly access class members in a callback function?

Answer №1

Here is an example to consider:

class DialogContent extends PopupBase implements OnInit {
    constructor(public popup: PopupRef) {
        super(popup);
    }
    
    ngOnInit(): void {
        this.handleBackButton();
    }
    
    public onClosePopup(): void {
        console.log("Closing popup", this.popup)
        this.popup.close({ popupClosed: true });
    }
    
    handleBackButton() {
        App.addListener('backButton', () => {
            this.onClosePopup(); //unable to access onClosePopup method within callback
        })
    }
}

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

Is it possible to utilize mathematical operators such as multiplication, division, addition, subtraction, and exponentiation to transform a non-zero numerical value into

I am currently working with Oracle Siebel software which supports JavaScript expressions using only specific operators such as multiply, divide, subtract, add, and XOR (*, /, -, +, ^). Unfortunately, other operators like ! or ? : are not available for use. ...

Creating stylish error labels using Materialize CSS

While Materialize has built-in support for validating input fields like email, I am looking to implement real-time validation for password inputs as well. This would involve dynamically adding error or success labels using JavaScript. Unfortunately, my at ...

Obtaining the blog slug dynamically upon clicking with ReactJS

Currently, I am developing a project using Reactjs and Nextjs. One of the tasks at hand is to obtain the "slug" value after clicking on a blog post. However, at this moment, the value returned is undefined despite trying the following code: <h4 onClic ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...

The closure in question received an undefined Angular parameter

Here is something similar to what I have: $scope.fetchData = function(path, save_to) { $http({method: 'GET', url: 'http://localhost:8001/www-root/' + path}). success(function(data, status, headers, config) { ...

Detecting whether a browser is capable of supporting dark mode

One method to determine if dark mode is active is by using prefers-color-scheme: dark: const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; Is there a way to detect if a browser supports dark mode as well? (By "supports ...

Accessing data from localhost using Vue.js and Axios is restricted due to CORS policy and the error "Access to XMLHttpRequest" may be

Having a minor issue... Trying to retrieve a basic json file from my server for testing purposes (not an actual API). Utilizing VueJS and axios. Here is my code : getServicesAPI() { axios.get("http://51.91..../dist/API/Services.json").the ...

Attempting to design a form that will trigger a print dialog box displaying all the information entered in the form

I am currently working on developing a form that will allow users to input information such as Name, Age, Gender, Hobbies, Contact details, and Photo in order to create a resume. My goal is to build a simple local HTML-based application that generates a RE ...

encountering an error of unsupported grant type while attempting to authenticate a user

I've seen a lot of discussions on this topic, but none have addressed my specific issue. Currently, I am working on an angular 5 application and trying to retrieve an authentication token by sending a post request to a server. Testing the connection ...

Leveraging JavaScript to trigger onClick() functions for multiple buttons throughout a webpage

        While searching for solutions, I came across several articles with similar topics, but unfortunately, none of the proposed solutions worked. Please forgive me if it was due to my own error. Background I am assisting a client who is transition ...

What is the mechanism behind pushing an empty array into another empty array?

let arr = []; console.log(arr.push([])); // 1 Instead of logging [[]], the output is 1. Can someone explain what is happening in the code above? ...

Trouble with Bootstrap 5 Dropdown Functionality

Currently, I am using Bootstrap 5 in conjunction with Django to create a website and I'm encountering difficulties with getting a dropdown feature to work properly. Despite copying the code directly from w3schools, it fails to function when I load the ...

Trouble arises when trying to import Jest with Typescript due to SyntaxError: Import statement cannot be used outside a module

Whenever I execute Jest tests using Typescript, I encounter a SyntaxError while importing an external TS file from a node_modules library: SyntaxError: Cannot use import statement outside a module I'm positive that there is a configuration missing, b ...

Having trouble decoding a cookie received from a React.js front-end on an Express server

When using React js for my front end, I decided to set a cookie using the react-cookie package. After confirming that the request cookie is successfully being set, I moved on to configure the Express server with the cookie parser middleware. app.use(cookie ...

How to Position Logo in the Center of MUI AppBar in React

I've been struggling to center align the logo in the AppBar. I can't seem to get the logo to be centered both vertically and horizontally on its own. Here is my code from AppBar.tsx: import * as React from 'react'; import { styled, useT ...

Creating functionality with a native JavaScript plugin within a directive and test suite

I have a custom JavaScript plugin that is integrated within a directive and utilized in an Angular manner. Snippet of the directive, export default function () { 'use strict'; return { restrict: 'E', scope: { map: &apo ...

Using Javascript Regular Expressions to validate that the first number in an amount is non-zero

Need a solution to only accept numbers that do not start with zero, but can contain zeros after the first digit. Currently using var.replace(/[^1-9]/g, ''); which prevents input of 0 altogether. Examples of valid inputs: 10 9990 Examples of in ...

A JavaScript function to separate a URL and eliminate the final segment

http://www.google.com/site!#656126.72367 Is there a way to split and remove the part after the exclamation mark in this URL using JavaScript when the page is loaded? I am looking to achieve http://www.google.com/site ...

Retrieve the value of a property with a generic type

Within our angular6 project, we encountered an issue while using the "noImplicitAny": true setting. We realized that this caused problems when retrieving values from generic types. Currently, we retrieve the value by using current['orderBy'], bu ...

Guidelines for integrating deep links into a ReactJS Ionic Android application

I have recently converted my ReactJS project into an android project following a tutorial. Now, I have successfully created an APK file and would like to configure the app to open when a specific URL is clicked on a mobile browser. Any guidance on how to a ...