Ionic 2 防止硬件后退按钮默认 [英] Ionic 2 prevent hardware back button default

查看:34
本文介绍了Ionic 2 防止硬件后退按钮默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在按下硬件后退按钮时阻止默认导航?我已经尝试过 registerBackButtonAction,但是它会覆盖我不想要的每个页面中的后退按钮的行为.

How can I prevent default navigation when pressing hardware back button? I've tried registerBackButtonAction, but then it overwrites behavior of back button in every page which I don't want.

这也没有帮助.

document.addEventListener("backbutton", (event) => {
      event.preventDefault();
  }, false);

推荐答案

正如你在 Ionic 文档 registerBackButtonAction 返回一个函数:

As you can see in Ionic docs registerBackButtonAction returns a function:

一个函数,当被调用时,将取消注册它的后退按钮行动.

A function that, when called, will unregister its back button action.

因此您可以使用该功能在离开页面时恢复默认行为,如下所示:

So you can use that function to restore the default behavior when leaving the page, like this:

import { Component} from '@angular/core';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    // Property used to store the callback of the event handler to unsubscribe to it when leaving this page
    public unregisterBackButtonAction: any;

    constructor(...) { ... }

    ionViewDidEnter() {
        this.initializeBackButtonCustomHandler();
    }

    ionViewWillLeave() {
        // Unregister the custom back button action for this page
        this.unregisterBackButtonAction && this.unregisterBackButtonAction();
    }

    public initializeBackButtonCustomHandler(): void {
        this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
            this.customHandleBackButton();
        }, 10);
    }

    private customHandleBackButton(): void {
        // do what you need to do here ...
    }
}

如你所见,关键是存储了registerBackButtonAction方法的回调,以后在离开页面时(或者想恢复默认行为时)使用:

So as you can see, the key is to store the callback of the registerBackButtonAction method and use it later when leaving the page (or when you want to restore the default behavior):

this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
    this.customHandleBackButton();
}, 10);

这篇关于Ionic 2 防止硬件后退按钮默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆