我只需要在我的根页面上调用该函数。但这会在所有页面上调用离子2

时间:2017-02-11 09:03:50

标签: angular typescript ionic-framework ionic2

我只需要在我的根页面上调用该函数。但这会在所有页面上调用离子2。 代码如下:

constructor(public platform: Platform,public alertCtrl:AlertController) {

        platform.ready().then(() => {
             platform.registerBackButtonAction(()=>this.myHandlerFunction())
            StatusBar.styleDefault();
            Splashscreen.hide();

        });
    }


    myHandlerFunction(){
        let alert = this.alertCtrl.create({
        title: 'Exit?',
        message: 'Do you want to exit the app?',
        buttons: [
          {
            text: 'Cancel',
            role: 'cancel',
            handler: () => {

            }
          },
          {
            text: 'Exit',
            handler: () => {
              this.platform.exitApp();
            }
          }
        ]
      });
      alert.present();

    }

我需要在myHandlerFunction()

上调用Homepage

1 个答案:

答案 0 :(得分:0)

您可以在app.component.ts中使用以下内容。

import { Component } from '@angular/core';
import { Platform,App, AlertController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

import {LognPage} from '../pages/logn/logn';

@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
  rootPage = LognPage;

  constructor(public platform: Platform,
              private alertCtrl: AlertController,
              public app: App) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();

       //Registration of push in Android and Windows Phone
      platform.registerBackButtonAction(() => {
        let nav = this.app.getActiveNav();
        if (nav.canGoBack()){ //Can we go back?
          nav.pop();
        }else{
          this.myHandlerFunction();
        }
      });
    });
  }

  myHandlerFunction(){
      let alert = this.alertCtrl.create({
      title: 'Exit?',
      message: 'Do you want to exit the app?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {

          }
        },
        {
          text: 'Exit',
          handler: () => {
            this.platform.exitApp();
          }
        }
      ]
    });
    alert.present();
  }   
}

{{3}}来自此主题的参考。

快乐的编码!!