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
,但我不知道爲什麼。
呈現的代碼對我來說很不錯。我會嘗試刪除HomeComponent並查看TokenComponent是否開始正常工作。用你的應用程序創建併發佈一個plunker會有所幫助。 –