ionic2 - 将模态添加为静态函数

时间:2017-03-26 07:26:31

标签: angular ionic2

我的static openModalInfo()中有app.component.ts个功能:

import { Platform, ModalController } from 'ionic-angular';
export class MyApp {
static modalCtrl:ModalController;
constructor(platform: Platform, 
              statusBar: StatusBar, 
              splashScreen: SplashScreen) {
    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();
    });
  }
static openModalInfo() {
    let modal = this.modalCtrl.create(ModalInfo);
    modal.present();
  }

}

我的想法是让所有modal都在MyApp,这样我就可以在发生错误时调用它:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import {MyApp} from '../../../app/app.component';//<-- add MyApp.

export class HomePage {

  constructor(public navCtrl: NavController) {

  }

onModal(){
  MyApp.openModalInfo();//<-- call this function.
}

}

但是我遇到了这个错误:

  

./HomePage类中的错误HomePage - 内联模板:34:6导致:   无法读取未定义的属性“创建”

我相信,create引用this.modalCtrl.create(ModalInfo)中的MyApp

我该如何解决这个问题?

或者我怎样才能创建一个通用模态函数,以便我可以从任何组件调用?

1 个答案:

答案 0 :(得分:0)

我建议您使用某种Utility Provider类,可以将其注入任何组件

@Injectable()
export class Utility{

  constructor(private modalCtrl: ModalController){}

  openModalInfo() {
     let modal = this.modalCtrl.create(ModalInfo);
     modal.present();
  }