我正在用角度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一無所知,所以我這樣做。
請注意:我減少了我的例子中的代碼,所以問題不是太長。
在NavigationService中,事件名爲toggleMenuEvent,在你的'main.ts'中你訂閱了'showMenuEvent'。 – rinukkusu
排字錯誤! –