Jan*_*yne 4 ionic-framework ionic-view ionic2 angular
我使用以下命令创建了一个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);
Run Code Online (Sandbox Code Playgroud)
我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');
}
}
Run Code Online (Sandbox Code Playgroud)
使用共享服务,您可以在整个应用程序中进行通信.
创建一个类似的服务类
@Injectable()
class SharedService {
// use any kind of observable to actively notify about new messages
someEvent:Subject = new Subject();
}
Run Code Online (Sandbox Code Playgroud)
在您的应用上提供它
@App({
...
providers: [SharedService]
})
Run Code Online (Sandbox Code Playgroud)
将它注入App组件以及要与App组件通信的任何组件,指令或服务
constructor(private sharedService:SharedService) {}
someEventHandler() {
this.sharedService.someEvent.next('some new value');
}
Run Code Online (Sandbox Code Playgroud)
在App组件中订阅通知
constructor(sharedService:SharedService) {
sharedService.someEvent.subscribe(event => {
if(event == ...) {
this.doSomething();
}
});
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html
使用Ionic 2,您可以使用事件进行组件之间的通信.例如,在您的函数中,buttonClicked()您可以触发事件
buttonClicked() {
this.events.publish('functionCall:buttonClicked', thisPage);
}
Run Code Online (Sandbox Code Playgroud)
并在它的主类的构造函数中监听它以打开模态:
this.events.subscribe('functionCall:buttonClicked', userEventData => {
openModal(userEventData[0]);
});
Run Code Online (Sandbox Code Playgroud)
您甚至可以使用该事件发送数据(此处:) thisPage.
| 归档时间: |
|
| 查看次数: |
7807 次 |
| 最近记录: |