我希望在更改路由器插座中的組件時更改動作欄鏈接。每個組件可能包含自己的一組動作鏈接,但也可能是空的,這意味着動作欄不會呈現任何內容。更改路線更改中的組件內容Angular 2
我有以下ContentComponent
模板:
<app-header></app-header>
<div class="page-container">
<app-sidebar-left></app-sidebar-left>
<div class="page-content-wrapper">
<div class="page-content">
<h1 class="page-title"> Product Builder
<small>Dashboard</small>
</h1>
<div class="page-bar">
<ul class="page-breadcrumb">
<li>
<i class="icon-home"></i>
<span>Dashboard</span>
</li>
</ul>
<app-action-bar></app-action-bar>
</div>
<router-outlet></router-outlet>
</div>
</div>
</div>
的<app-action-bar>
包含以下HTML:
<div *ngIf="links.length" class="page-toolbar">
<div class="btn-group pull-right">
<button type="button" class="btn btn-fit-height grey-salt dropdown-toggle" data-toggle="dropdown"
data-hover="dropdown" data-delay="1000" data-close-others="true" aria-expanded="true"> Actions
<i class="fa fa-angle-down"></i>
</button>
<ul class="dropdown-menu pull-right" role="menu">
<li *ngFor="let link of links">
<a [routerLink]="[link.url]">{{ link.text}}</a>
</li>
</ul>
</div>
</div>
我用下面的操作杆組件連接服務: action-bar.component.ts
import {Component} from "@angular/core";
import {ActionService} from "../../../services/application/action.service";
@Component({
selector: 'app-action-bar',
templateUrl: './action-bar.component.html',
styleUrls: ['./action-bar.component.scss']
})
export class ActionBarComponent {
private links = [];
constructor(private actionService: ActionService) {
this.actionService.getLinks().subscribe(link => {
this.links.push(link);
});
}
}
action.service.ts
import {Injectable} from "@angular/core";
import {Subject} from "rxjs/Subject";
import {Observable} from "rxjs";
import {ILink} from "../../interfaces/linkinterface";
@Injectable()
export class ActionService {
private links = new Subject<ILink>();
addLink(linkText: string, url: string) {
this.links.next({text: linkText, url: url});
}
purgeLinks() {
this.links = new Subject<ILink>();
}
getLinks(): Observable<any> {
return this.links.asObservable();
}
}
linkinterface.ts
export interface ILink {
text: string;
url: string;
}
在A組份我已經添加任何鏈接。當這個組件首先被加載時,動作欄是空的。好結果。 組件B包含2個鏈接,使用OnInit。操作欄包含2個鏈接。好結果。 組件C不包含鏈接。操作欄仍然包含2個鏈接,這應該是空的。結果不好。
我對此很新,所以我可能會錯過一些非常簡單的東西。請幫我看看它是什麼。
請分享組件A,B和C的代碼。我是你不從組件C中獲取可由ActionBarComponent監聽的組件,而組件仍然顯示組件B的2個鏈接。 –
也嘗試在ActionBarComponent構造函數: this.actionService.getLinks()。subscribe(link => { this.links.length = 0; this.links.push(link); }); –
謝謝你的迴應。組件A和C的代碼是沒有用的,只是渲染一個視圖就足夠了。組件B包含一個'OnInit',它包含以下'this.actionService.addLink('元素toevoegen','/ elements/add');'這個負責傳遞鏈接到ActionBar。 – Roberto