2017-06-04 151 views
0

目前我正在使用Angular4。現在我有一個問題。我有這個HeaderService改變在HeaderComponent標題:事件不發射

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

@Injectable() 
export class HeaderService { 

    @Output() 
    public fire: EventEmitter<String> = new EventEmitter(); 

    constructor() { 
    } 

    public changeTitle(title: string) { 
     console.log("Want to change title to: " + title); 

     this.fire.emit(title); 
    } 

    public getTitle(): EventEmitter<String> { 
     return this.fire; 
    } 

} 

這是我HeaderComponent

import {Component, EventEmitter, OnInit} from "@angular/core"; 
import {HeaderService} from "../../services/header.service"; 

@Component({ 
    selector: 'header', 
    templateUrl: './header.component.html' 
}) 
export class HeaderComponent implements OnInit { 

    private title: string = "felixoi.net"; 
    private subscription: EventEmitter<String>; 

    constructor(private headerService: HeaderService) { 
    } 

    ngOnInit(): void { 
     console.log("Loading HeaderComponent"); 

     this.subscription = this.headerService.getTitle().subscribe((title: string) => { 
      console.log("Changed title to: " + title); 

      this.title = title; 
     }); 
    } 
} 

在我HomeComponent我使用這項服務來改變標題:

import {Component, OnInit} from '@angular/core'; 
import {HeaderService} from "../shared/services/header.service"; 

@Component({ 
    selector: 'home', 
    templateUrl: './home.component.html' 
}) 
export class HomeComponent implements OnInit { 

    constructor(private headerService: HeaderService) { 
    } 

    ngOnInit(): void { 
     console.log("Loading HomeComponent"); 

     this.headerService.changeTitle("Home"); 
    } 

} 

我在我的TokenService中有完全相同的調用,但在此組件中,相同的代碼不起作用。

import { Component } from '@angular/core'; 
import {HeaderService} from "../shared/services/header.service"; 

@Component({ 
    selector: 'token', 
    templateUrl: './token.component.html' 
}) 
export class TokenComponent implements OnInit { 

    constructor(private headerService: HeaderService) { 
    } 

    ngOnInit(): void { 
     console.log("Loading TokenComponent"); 

     this.headerService.changeTitle("Tokens"); 
    } 

} 

我在我的代碼中創建了一些調試消息。這是控制檯輸出:

Loading HeaderComponent 
Loading HomeComponent 
Want to change title to: Home 
Changed title to: Home 
Loading TokenComponent 
Want to change title to: Tokens 

它表明事件不會發出對TokenComponent,但我不知道爲什麼。

+0

呈現的代碼對我來說很不錯。我會嘗試刪除HomeComponent並查看TokenComponent是否開始正常工作。用你的應用程序創建併發佈一個plunker會有所幫助。 –

回答

0

我發現了這個問題。

該模塊是導入乘法次數,因此存在不同的實例,也有不同的發射器可供訂閱。