如何在Angular 7中实现面包屑

时间:2018-11-30 06:48:21

标签: angular breadcrumbs angular7

我正在尝试在基于Angular 7的应用程序中实现面包屑。

下面提到了包含面包屑组件的根组件的HTML模板(面包屑在路由器出口外部)

<app-layout>
 <div>
  <app-breadcrumb></app-breadcrumb>
  <router-outlet></router-outlet>
 </div>
</app-layout>

面包屑ts文件

ngOnInit() {
 this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((router) => {
  let snapshot = this.router.routerState.snapshot;
  this.breadcrumbs = [];
  let url = snapshot.url;
  let routeData: Data = snapshot.root.data;
  let label = routeData['breadcrumb'];
  let params = snapshot.root.params;
  this.breadcrumbs.push({
    url: url,
    label: label,
    params: params
  });
});

面包屑组件html文件

<nav aria-label='breadcrumb'>
  <ol class='breadcrumb'>
    <li *ngFor='let breadcrumb of breadcrumbs'>
      <a [routerLink]='[breadcrumb.url, breadcrumb.params]' routerLinkActive='active'>{{ breadcrumb.label }}</a>
    </li>
  </ol>
</nav>  

路由定义如下

const routes: Routes = [
 { path: 'folders', component: FolderManagementComponent, data: { breadcrumb: 'Home' } },
 { path: 'folders/list-documents', component: ListDocumentsComponent, data: { breadcrumb: 'Documents' } },
 { path: '', redirectTo: '/folders', pathMatch: 'full', data: { breadcrumb: 'Home' }}
];

但是我没有得到数据和参数

1 个答案:

答案 0 :(得分:1)

使用以下代码更新面包屑组件ts文件中的路由器订阅逻辑。

  ngOnInit() {

    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .pipe(map(() => this.activatedRoute))
      .pipe(map((route) => {
        while (route.firstChild) { route = route.firstChild; }
        return route;
      }))
      .pipe(filter(route => route.outlet === PRIMARY_OUTLET))
      .subscribe(route => {

        let snapshot = this.router.routerState.snapshot;
        this.breadcrumbs = [];
        let url = snapshot.url;
        let routeData = route.snapshot.data;

        console.log(routeData);
        let label = routeData['breadcrumb'];
        let params = snapshot.root.params;

        this.breadcrumbs.push({
          url: url,
          label: label,
          params: params
        });

      });

}

正在运行的stackblitz链接:https://stackblitz.com/edit/breadcrumb-in-angular-7

最近,我已经实现了ng7-dynamic-breadcrumbng7-bootstrap-breadcrumbng7-mat-breadcrumb Angular面包屑模块​​。请检查这些模块,希望对动态面包屑有所帮助。