Angular2路由器,从url获取路由数据,显示面包屑

Angular2 router, get route data from url, to display breadcrumbs

我正在使用 angular2 router

要绘制 url 的面包屑导航,假设是站点。com/a/b/c/15 我执行以下操作:

  1. 获取site.com/a/b/c/15的路由并获取与该路由关联的漂亮名称
  2. 获取site.com/a/b/c的路由并获取与该路由关联的漂亮名称
  3. 获取site.com/a/b的路由并获取与该路由关联的漂亮名称
  4. 获取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'}},

我的过程的结果将是一个包含 {"I am C", "I am B", "I am C"} 的数组,因此我可以显示一个很好的面包屑 "I am A > I am B > I am C" 来解释当前路线。

这用于与不推荐使用的路由器一起工作

this.router.recognize(url).then((instruction) => {
    instruction.component.routeData.get('prettyName') // Would return 'I am ..'

然而现在;使用最后一个路由器,我无法再处理此识别逻辑。

如何获取与url关联的路线数据?

到目前为止,最可行的解决方案是(完成):

  • 制作路线export/importable
  • 从 router.events 订阅获取当前 url 更新
  • 在 url 改变时,在路由路径上循环,查看模式是否匹配 url
  • 如果模式匹配url,从匹配的路由中获取数据

优点:有效

缺点:重做url-不使用 ng2 router one 的手动路由识别

已针对 RC5 更新

不是从当前 URL 开始并尝试从 URL 获取路线,而是可以从 [=12] 获取所有激活的路线(与主要出口相关联) =]:

After the end of each successful navigation lifecycle, the router builds a tree of ActivatedRoutes, which make up the current state of the router. We can access the current RouterState from anywhere in our application using the Router service and the routerState 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. -- reference

订阅路由器事件,然后,在每个 NavigationEnd 事件之后,从 root:

沿着 ActivatedRoute 的树向下走
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


另请参阅 以获得类似的解决方案。

任何面包屑解决方案都必须处理 -

  1. 在应用程序路由中定义面包屑的声明式方法。
  2. 使用服务器响应中的标签更新任何路由的动态异步方式。
  3. 在面包屑中跳过特定路线显示的方法。

我创建了一个 Angular 库来处理所有这些,称为 xng-breadcrumbs - https://github.com/udayvunnam/xng-breadcrumb

随时检查,开发的 Angular 应用程序显示面包屑使用情况 - https://xng-breadcrumb.netlify.com

Angular库规划、创建和持续发布很好documented in this medium article