更新为 RC5
您可以从以下位置获取所有激活的路由(与主出口相关联),而不是从当前 URL 开始并尝试从 URL 获取路由RouterState
:
在每个成功的导航生命周期结束后,路由器都会构建一棵ActivatedRoute
s 树,它们构成了路由器的当前状态。我们可以使用服务和属性RouterState
从应用程序中的任何位置访问电流。Router
routerState
路由器状态为我们提供了从任何激活的路由向上和向下遍历路由树的方法,以从父、子和兄弟路由中获取我们可能需要的信息。--参考
订阅路由器事件,然后,在每个事件之后,从 sNavigationEnd
的树向下走:ActivatedRoute
root
import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/filter';
@Component({
selector: 'breadcrumbs',
template: `
<div>
breadcrumbs:
<span *ngFor="let breadcrumb of breadcrumbs; let last = last">
<a [routerLink]="breadcrumb.url">{{breadcrumb.label}}</a>
<span *ngIf="!last">></span>
</span>
</div>`
})
export class BreadcrumbsComponent {
breadcrumbs: Array<Object>;
constructor(private router:Router, private route:ActivatedRoute) {}
ngOnInit() {
this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(event => { // note, we don't use event
this.breadcrumbs = [];
let currentRoute = this.route.root,
url = '';
do {
let childrenRoutes = currentRoute.children;
currentRoute = null;
childrenRoutes.forEach(route => {
if(route.outlet === 'primary') {
let routeSnapshot = route.snapshot;
console.log('snapshot:', routeSnapshot)
url += '/' + routeSnapshot.url.map(segment => segment.path).join('/');
this.breadcrumbs.push({
label: route.snapshot.data.breadcrumb,
url: url });
currentRoute = route;
}
})
} while(currentRoute);
})
}
}
路线如下所示:
{ path: '', component: HomeComponent, data: {breadcrumb: 'home'}}
Plunker- RC.5,路由器 3.0.0-rc.1
另请参阅https://stackoverflow.com/a/38310404/215945以获得类似的解决方案。