私は、HeaderComponentのルートコンセントコンポーネントにいくつかのデータが必要です。データルータのアウトレットコンポーネントをHeaderComponentに取得する方法は?
私の下の画像を確認してください。
私は、HeaderComponentのルートコンセントコンポーネントにいくつかのデータが必要です。データルータのアウトレットコンポーネントをHeaderComponentに取得する方法は?
私の下の画像を確認してください。
あなたは共有流通サービスからイベントを発するなど、あなたのヘッダー・コンポーネントに、このイベントを購読することができます。サービスで
onEvent() {
this.sharedService.changeTitle(newTitle);
}
:あなたの現在のルートコンポーネントに
:
titleChanged = new EventEmitter();
changeTitle(title) {
this.titleChanged.emit(title);
}
hea DERコンポーネント:
title: string = '';
ngOnInit(){
this.sharedService.titleChanged.subscribe(title => this.title = title);
}
投稿は非常に便利です。しかし、いくつかのあなたの投稿に間違っています。 –
どのようなエラーが発生しますか? "onEvent"は単なるサンプル名です。コード内でタイトルの変更箇所からこのメソッドを呼び出すことができます... – MatWaligora
ok ...申し訳ありませんが、エラーではありません。 –
1)
import {Injectable, EventEmitter} from "@angular/core";
@Injectable()
export class AdminService {
titleChanged = new EventEmitter();
constructor() {}
changeTitle(title) {
this.titleChanged.emit(title);
}
}
2)
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をapp.component.ts admin.service.ts .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");
}
}
あなたは 'sharedService'を使うべきです。サービスデータはコンポーネント間で共有されます。 – micronyks
@micronyks:私はsharedServiceの使用を知っています。しかし、1つの問題。私のヘッダーのタイトルを自動的に変更するには? –