简体   繁体   中英

Access Class Members within a call back function Angular12 and Capacitor V-3

I am using the below code to navigate to parent component on click of "Device Hardware Back Button". I am using Capacitor 3.0 and device backbutton works properly. Actual issue is that i am not able to access Class members in the callback function.

Below is the code

  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 available thru arrow or callback functions
      }
    
  handleHardwareBackButton(){
   App.addListener('backButton',function(){
    this.onCancelAction() //not able to access onCancelMethod within callback
   })
  }

    }

Issue is that i am getting "this.onCancelAction" is not a method. Also i tried below code but no use.

handleHardwareBackButton(){
   App.addListener('backButton',function(){
    this.dialog.close({ actionConfirmed : false }); //here this line doesn't get executed. Also no errors observed
   }.bind(this))
  }

Am i going wrong somewhere? Please guide me on how to access class members in a callback function?

Try something like this...

export class ConfirmBoxComponent extends DialogContentBase implements OnInit {
    constructor(public dialog: DialogRef) {
        super(dialog);

    }
    ngOnInit(): void {
        this.handleHardwareBackButton();
    }

    public onCancelAction(): void {
        console.log("Cancel confirmed", this.dialog)
        this.dialog.close({ actionConfirmed: false });
    }

    handleHardwareBackButton() {
        App.addListener('backButton', () => {
            this.onCancelAction() //not able to access onCancelMethod within callback
        })
    }
}

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