2016-05-18 82 views
1

我正在用角度cli的一點幫助編寫我的第一個Angular2應用程序。我正在嘗試爲漢堡包菜單編寫一個可用於較小屏幕的顯示/隱藏切換功能。我的應用程序佈局看起來像這樣:父組件無法檢測到簡單的EventEmitter - Angular2

|-- app 
    |-- src 
     |-- navigation 
      |-- navigation.component.ts 
      |-- navigation.service.ts 
      |-- navigation.template.html 
     |-- main.ts 
     |-- main.template.html 
     |-- system-config.ts 
    |-- index.html 

現在我只想要一個簡單的功能,當我點擊一個按鈕,在我的navigation.template.html,像這樣:

<button type="button" class="navbar-toggle collapsed" (click)="toggleMenu()"> 
    <span class="sr-only">Toggle navigation</span> 
    <span class="icon-bar"></span> 
    <span class="icon-bar"></span> 
    <span class="icon-bar"></span> 
</button> 

click事件調用的方法在我navigation.component.ts像這樣

togMenu: boolean = false; 
//... more code then, 

toggleMenu(): void { 
    this.togMenu = !this.togMenu; 
    this.navigationService.toggleMenuEvent.emit(this.togMenu); 
} 

,在同一文件夾中使用服務用下面的代碼:

import {Injectable, EventEmitter} from '@angular/core'; 

@Injectable() 
export class NavigationService { 
    toggleMenuEvent: EventEmitter<boolean> = new EventEmitter(); 
} 

沒有什麼,偉大的,但我需要在main.template.html的Emmitted值,所以我在類的構造函數中的main.ts文件偵聽事件發射器:

showMenu: boolean = false; 

    constructor(private navigationService: NavigationService) { 
     navigationService.toggleMenuEvent.subscribe(
      (val) => { 
       this.showMenu = val; 
      }); 
    } 

然而,在該事件沒有回升父組件。它沒有被聽到/識別,因此showMenu變量總是爲false。我應該將名稱代碼放入子組件中嗎?可以聽到該事件,但似乎沒有冒泡到父組件(main)。我做錯了什麼。請注意,我的控制檯中沒有錯誤,我正在使用Angular2的候選版本。

我一直在尋找這個網站和其他地方,建議使用Observable而不是Event Emitter,我對Observables一無所知,所以我這樣做。

請注意:我減少了我的例子中的代碼,所以問題不是太長。

+0

在NavigationService中,事件名爲toggleMenuEvent,在你的'main.ts'中你訂閱了'showMenuEvent'。 – rinukkusu

+0

排字錯誤! –

回答

1

我想這是您的服務實例範圍的問題。我的意思是有你這樣引導您的應用程序時,例如需要定義有一個共享服務:

bootstrap(AppComponent, [ NavigationService ]); 

,而不是在他們providers屬性的部件重新定義它。這樣你將共享相同的實例,並能夠共享事件發射器。

請注意,您應該在共享服務中使用ObservableSubject而不是EventEmitterEventEmitter僅用於實現組件中的自定義事件。

+0

我已經將該服務添加到'bootstrap',並且沒有在組件的providers屬性中重複它。我會考慮使用Observables或Subjects,而我只是不能/沒有找到一個示例/教程 –

+0

也許這個鏈接的示例:https://angular.io/docs/ts/latest/cookbook/component- communication.html#!#雙向服務;-) –

+2

太棒了!感謝您的鏈接......哦,你是對的...... main.ts中'providers'屬性有重複! –