Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nativescript angular : handle android back button on different pages

Tags:

nativescript

So I use this function to handle android back button :

this._page.on(Page.loadedEvent, event => {
        if (application.android) {
            application.android.on(application.AndroidApplication.activityBackPressedEvent, (args:AndroidActivityBackPressedEventData) => {      
                args.cancel = true;
                this._ngZone.run(() => {
                this.router.navigate(['/parameters']);
                });
            });
        }
    })   

on different pages (angular components). So on page1.ts I have navigate(['/parameters]) and on page2.ts I have console.log("test"). Problem is wherever I am in the app, pressing back button always do navigate(['/parameters]), also the console.log if i'm on the right page, but it should do console.log only. It seems to be global, any idea how to override activityBackPressedEvent ?

like image 273
Pac Avatar asked Dec 24 '22 00:12

Pac


1 Answers

activityBackPressedEvent is not specific to a page, it's global to your Activity which holds all the pages. Generally, You will not add more than one event listener to this event.

You could do something like below to handle this on page level, probably in app module / main.ts

application.android.on(application.AndroidApplication.activityBackPressedEvent,
    (args: application.AndroidActivityBackPressedEventData) => {
        const page = frame.topmost().currentPage;
        if (page.hasListeners(application.AndroidApplication.activityBackPressedEvent)) {
            args.cancel = true;
            page.notify({
                eventName: application.AndroidApplication.activityBackPressedEvent,
                object: page
            });
        }
    });

With above code, activityBackPressedEvent willl be triggered on every page that has a listener.

Now in your page / component in which you want to customise the behaviour you do this,

// Inject Page
constructor(private page: Page) { 
   this.page.on(application.AndroidApplication.activityBackPressedEvent, this.onBackButtonTap, this);
}

onBackButtonTap(data: EventData) {
            this._ngZone.run(() => {
                this.router.navigate(['/parameters']);
            });
}
like image 151
Manoj Avatar answered Dec 28 '22 06:12

Manoj