registerBackButtonAction,Ionic2,用于不同的页面

raj*_*aju 6 typescript ionic-framework ionic2 ionic3 angular

我正在开发一个Ionic2应用程序.我对registerBackButtonAction功能感到困惑.

我在一个页面上做了这个(比如pageA).它按预期工作.

this.platform.registerBackButtonAction(() => {
     console.log("back presed");
    this.abortDownloadAndExit();
    });
Run Code Online (Sandbox Code Playgroud)

现在我想registerBackButtonAction在其他页面上做一些其他操作(比如PageB).但Ionic正在从pageA采取行动

如何在不同页面上注册不同的作品.

seb*_*ras 14

正如您在Ionic docs中 看到的那样,registerBackButtonAction返回一个函数:

一个函数,当被调用时,将取消注册其后退按钮操作.因此,您可以使用该功能在离开页面时恢复默认行为,如下所示:

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 ...
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,关键是存储registerBackButtonAction方法的回调并在以后离开页面时使用它(或者当您想要恢复默认行为时):

this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
    this.customHandleBackButton();
}, 10);
Run Code Online (Sandbox Code Playgroud)