我正在使用 angular2 router.
要绘制一个url的面包屑,让我们说site.com/a/b/c/15我做了以下:
>获取site.com/a/b/c/15的路由,并获取与路由关联的漂亮名称
>获取site.com/a/b/c的路由,并获取与路由关联的漂亮名称
>获取site.com/a/b的路由,并获取与路由关联的漂亮名称
>获取site.com/a的路由,并获取与路由关联的漂亮名称
所以说我确实有以下路线:
{ path: 'a',component: A,data:{prettyName: 'I am A'}} { path: 'b',component: B,data:{prettyName: 'I am B'}},{ path: 'c',component: C,data:{prettyName: 'I am C'}},
我的过程的结果将是一个包含{“我是C”,“我是B”,“我是C”}的数组,并且感谢我可以显示一个很好的面包屑“我是A>我是B>我是C“,解释了目前的路线.
这个用来与路由器一起使用的已经弃用了
this.router.recognize(url).then((instruction) => { instruction.component.routeData.get('prettyName') // Would return 'I am ..'
不过现在与最后一个路由器,我不能处理这个识别逻辑了.
如何获取与URL相关联的路由数据?
您可以从RouterState获取所有激活的路由(与主要插座相关联),而不是从当前URL开始并尝试从URL获取路由:
After the end of each successful navigation lifecycle,the router builds a tree of
ActivatedRoute
s,which make up the current state of the router. We can access the currentRouterState
from anywhere in our application using theRouter
service and therouterState
property.The router state provides us with methods to traverse up and down the route tree from any activated route to get information we may need from parent,child and sibling routes. — 07000
订阅路由器事件,然后,在每个NavigationEnd事件之后,从根目录下移动ActivatedRoutes树:
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