如何从导航到Ionic 2的页面访问主要组件的功能?

时间:2016-06-28 04:28:13

标签: angular ionic-framework ionic2 ionic-view

我使用以下命令创建了Ionic v2应用程序:

ionic start my-app sidemenu --v2 --ts

app.ts文件中,我有一些逻辑(函数)来做一些事情(比如打开一个模态并保持侧面菜单应该显示的状态)。当显示某个页面(例如pages/getting-started/getting-started.ts)时,我想在app.ts中重复使用相同的功能。如何从导航到?

的页面访问app.ts的功能

我的app.ts如下所示。

class MyApp {
 @ViewChild(Nav) nav:Nav;
 private rootPage:any = GettingStartedPage;
 private pages:any;

 constructor(platform:Platform) {
  this.initializeApp();
  this.pages = { 
   'GettingStartedPage': GettingStartedPage, 
   'AnotherPage': AnotherPage //more pages and modals
  };
 }

 initializeApp() {
  this.platform.ready().then(() => {
   StatusBar.styleDefault();
  });
 }

 openPage(page:string) {
  //when a user clicks on the left menu items, a new page is navigated to
  let component this.pages[page];
  this.nav.setRoot(component);
 }

 openModal(page:string) {
  //modals are opened here, there's more complicated logic
  //but this serves to demonstrate my problem
  let component = this.pages[page];
  Modal.create(component);
 }
}

ionicBootstrap(MyApp);

我的getting-started.ts如下所示。

export class GettingStartedPage {
 constructor(
  platform:Platform, 
  viewController:ViewController,
  navController:NavController,
  navParams:NavParams) {
 }

 buttonClicked() {
  //i need to access app.ts openModal here
  //how do i call a method on app.ts?
  //like MyApp.openModal('SomeModal');
 }
}

3 个答案:

答案 0 :(得分:9)

使用共享服务,您可以在整个应用程序中进行通信。

创建一个类似

的服务类
@Injectable() 
class SharedService {
  // use any kind of observable to actively notify about new messages
  someEvent:Subject = new Subject(); 
}

在您的应用上提供

@App({
  ...
  providers: [SharedService]
})

将其注入App组件以及要与App组件通信的任何组件,指令或服务

constructor(private sharedService:SharedService) {}

someEventHandler() {
  this.sharedService.someEvent.next('some new value');
}

App组件中订阅通知

constructor(sharedService:SharedService) {
  sharedService.someEvent.subscribe(event => {
    if(event == ...) {
      this.doSomething();
    }
  });
}

有关详细信息,请参阅to_timedelta

答案 1 :(得分:5)

使用Ionic 2,您可以使用Events进行组件之间的通信。例如,在您的函数buttonClicked()中,您可以触发事件

buttonClicked() {
  this.events.publish('functionCall:buttonClicked', thisPage);
}

并听取它,例如在主类的构造函数中打开模态:

this.events.subscribe('functionCall:buttonClicked', userEventData => { 
  openModal(userEventData[0]);
});

您甚至可以通过活动发送数据(此处为:thisPage)。

答案 2 :(得分:0)

或者,您可以选择

Events

  

Events是一个发布 - 订阅样式事件系统,用于发送和发送   响应您应用中的应用级事件。

EventEmitter

  

EventEmitter是一个angular2抽象,它的唯一目的是   在组件中发出事件。