2016-09-18 63 views

回答

2

您可以從共享服務隊發出事件和訂閱此事件在喜歡你的頭組件:在當前的路線組件

onEvent() { 
    this.sharedService.changeTitle(newTitle); 
} 

服務:

titleChanged = new EventEmitter(); 

changeTitle(title) { 
    this.titleChanged.emit(title); 
} 

in hea DER組件:

title: string = ''; 
ngOnInit(){ 
    this.sharedService.titleChanged.subscribe(title => this.title = title); 
} 
+0

你的帖子非常有用。但是,您的帖子中有一些錯誤。 –

+0

你會得到什麼錯誤? 「onEvent」只是一個示例名稱,您可以從代碼中標題更改的位置調用此方法... – MatWaligora

+0

好的...抱歉,沒有錯誤。 –

0

1)admin.service.ts

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

@Injectable() 
export class AdminService { 
    titleChanged = new EventEmitter(); 

    constructor() {} 

    changeTitle(title) { 
     this.titleChanged.emit(title); 
    } 
} 

2)app.component.ts

import { Component } from '@angular/core'; 
import {ActivatedRoute} from '@angular/router'; 
import { AdminService } from '../common/service/admin.service'; 

@Component({ 
    selector: 'app-admin', 
    //providers: [AdminService], 
    template: ` 
    <left-menu></left-menu> 
    <div class="main-panel"> 
     <app-header [header_title]="_header_title"></app-header> 
     <div class="content"> 
      <div class="container-fluid"> 
      <div class="row"> 
       <router-outlet></router-outlet> 
      </div> 
      </div> 
     </div> 
    <app-footer></app-footer> 
    </div> 

    ` 
}) 
export class AdminComponent { 

    public _header_title:string = ""; 
    constructor(route: ActivatedRoute,private _admin: AdminService) { 
     this._admin.titleChanged.subscribe(title => this._header_title = title); 
    } 
} 

3)用戶profile.component .ts

import { Component } from '@angular/core'; 
import { AdminService } from '../common/service/admin.service'; 

@Component({ 
    selector: 'user-profile', 
    templateUrl : `./app/user-profile/user-profile.component.html` 
}) 
export class UserProfileComponent { 
    private username:string="Bharat Chauhan"; 
    constructor(private _admin: AdminService) { 
     this._admin.changeTitle("User Profile"); 
    } 
} 
相關問題