我使用以下命令创建了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');
}
}
答案 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是一个发布 - 订阅样式事件系统,用于发送和发送 响应您应用中的应用级事件。
EventEmitter是一个angular2抽象,它的唯一目的是 在组件中发出事件。