Nativescript angular : handle android back button on different pages

99封情书 提交于 2019-12-08 05:02:55

问题


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 ?


回答1:


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']);
            });
}



回答2:


I think since you added the handle back button in the event pageLoaded that's why it does not work on other page.

The code that handle back button should be placed in the app starter. I'm using NS Vue & I place this code in my main.js. I think it could be similar in NS angular.

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


来源:https://stackoverflow.com/questions/55297104/nativescript-angular-handle-android-back-button-on-different-pages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!