2016-06-28 74 views
3

我使用以下命令創建了一個Ionic v2應用程序:如何從導航到Ionic 2的頁面訪問主要組件的功能?

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'); 
} 
} 

回答

6

通過共享服務,您可以跨整個應用程序進行通信。

創建像

@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(); 
    } 
    }); 
} 

詳見https://angular.io/docs/ts/latest/cookbook/component-communication.html

5

具有離子2,你可以使用Events組件之間的通信。例如,在你的函數buttonClicked()你可以觸發一個事件

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

,聽它例如在主類的構造函數打開模式:

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

你甚至可以與事件(:thisPage這裏)發送數據。

0

或者,你可以去任何

Events

活動是發佈 - 訂閱式的事件系統發送和 在您的應用程序響應應用程序級事件。

EventEmitter

EventEmitter是angular2抽象和其唯一目的是 發射在組件的事件。

0
頁面組件TS文件

import { MyApp } from '../../app/app.component'; 

constructor(public AppComponent: MyApp) { 
    } 

那麼無論你想訪問該功能內頁:

this.AppComponent.functionName();