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

前端之家收集整理的这篇文章主要介绍了Angular2路由器,从url获取路由数据,显示面包屑前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。



我正在使用 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相关联的路由数据?

更新为RC5

您可以从RouterState获取所有激活的路由(与主要插座相关联),而不是从当前URL开始并尝试从URL获取路由:

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. — 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

另见http://stackoverflow.com/a/38310404/215945类似的解决方案.

原文链接:https://www.f2er.com/angularjs/143095.html

猜你在找的Angularjs相关文章