【问题标题】:Angular 2 Dynamic BreadcrumbsAngular 2 动态面包屑
【发布时间】:2018-01-28 19:52:48
【问题描述】:

我需要一些关于面包屑的帮助

这里是路由配置示例

Routes = [  
    {path: '', redirectTo: 'home', pathMatch: 'full'},  
    {path: 'home', ..., data: { breadcrumb: 'Home'}},  
    {path: 'about', ..., data: { breadcrumb: 'About'}},  
    {path: 'github', ..., data: { breadcrumb: 'GitHub'},
    {
       path: 'category/:id',
       component: CategoryComponent
    },  
]

在面包屑组件中,我尝试使用它从ActivatedRoute中提取面包屑数据

ngOnInit() {
   // subscribe to the NavigationEnd event
   this.router.events.filter((event) => event instanceof NavigationEnd).subscribe(() => {

      // set breadcrumbs
      const root: ActivatedRoute = this.activatedRoute.root;
      this.breadcrumbs = this.getBreadcrumbs(root);
   });
 }

然后我渲染comonentns模板

<ul class="breadcrumb">
   <li><a routerLink="" routerLinkActive="active"><i class="fa fa-home position-left"></i> Главная</a></li>
   <ng-container *ngFor="let breadcrumb of breadcrumbs">
   <li routerLinkActive="active">
      <a [routerLink]="[breadcrumb.url, breadcrumb.params]"> {{ breadcrumb.label }}</a>
   </li>
   </ng-container>
</ul>

一切正常,但我不知道如何从另一个组件传递 category/:id 路由的数据值,以便像“手机”这样的人类可读路径

【问题讨论】:

  • 我猜你正在寻找在组件之间传递数据,这个答案可能会帮助stackoverflow.com/a/43766767/2708210
  • 您找到解决方案了吗?
  • 嗨@Grey2k 可以分享getBreadcrumbs() 功能吗?

标签: angular router breadcrumbs


【解决方案1】:

我希望现在回答这个问题还为时不晚 :D,所以这是一个有效的 CodeSandbox 示例,其中包含两个面包屑实现,它使用 router data 选项来传递和收集面包屑的数据。

代码说明:

查看面包屑组件内的 cmets。

这里是 breacrumb 组件

import { Component, OnInit } from "@angular/core";
import {
  Router,
  Event,
  ActivationStart,
  ActivatedRouteSnapshot,
  ActivationEnd,
  NavigationEnd,
  NavigationStart
} from "@angular/router";
import { filter, map, buffer, pluck } from "rxjs/operators";

/**
 * Check if an angular router 'Event' is instance of 'NavigationEnd' event
 */
const isNavigationEnd = (ev: Event) => ev instanceof NavigationEnd;
/**
 * Check if an angular router 'Event' is instance of 'NavigationEnd' event
 */
const isActivationEnd = (ev: Event) => ev instanceof ActivationEnd;

@Component({
  selector: "app-breadcrumb",
  templateUrl: "./breadcrumb.component.html",
  styleUrls: ["./breadcrumb.component.scss"]
})
export class BreadcrumbComponent implements OnInit {
  bcLoadedData;
  bcForDisplay;

  constructor(private router: Router) {}

  ngOnInit() {
    /**
     * navigationEnd$ is trigered once per completed routing event, in other words
     * once per loading a component that is in the end of the current route
     */
    const navigationEnd$ = this.router.events.pipe(filter(isNavigationEnd));

    /**
     * Here we subscribe to all navigation events, in order to update
     * our route "data", which we will use for the breadcrumb visualization.
     *
     * Than we filter the events emitted from the `router` in such way, that we are only
     * taking action upon a completed router event (in other words we are subscribing only for `ActivationEnd`
     * events)
     *
     * We use pluck to get only the requried bredcrumb data
     *
     * The buffer operator accumulates all `data` coming from the router and emmits the accumulated data once
     * when a `NavigationEnd` event passes troufh `navigationEnd$`
     *
     * The `map` in the end is used to reverse the collected data, in order to convert it to more logical
     * sequence. Without the revers first we will get the data for the current route, after that for it's parent
     * and so on (that is how the ng router works).
     */
    this.router.events
      .pipe(
        filter(isActivationEnd),
        pluck("snapshot"),
        pluck("data"),
        buffer(navigationEnd$),
        map((bcData: any[]) => bcData.reverse())
      )
      .subscribe(x => {
        this.bcLoadedData = x;
      });
  }
}
.breadcrumb {
    display: flex;

    &.simple {
        border: 2px solid blueviolet;
        border-radius: 4px;
    }

    .breadcrumb-separator {
        margin: 10px;
    }
}
<div class="breadcrumb simple">
    <div *ngFor="let bcElement of bcLoadedData; let last = last">
        {{bcElement.bc}}
        <span class="breadcrumb-separator"
              *ngIf="!last">></span>
    </div>
</div>

这是路线的结构

const routes: Routes = [
	{ path: '', pathMatch: 'full', component: MockComponentComponent, data: { bc: 'Looking outside' } },
	{
		path: 'home', component: MockComponentComponent,
		data: { bc: 'I see a home' },
		children: [
			{
				path: 'primaryHouse', component: MockComponentComponent,
				data: { bc: 'I\'m going inside the home' },
				children: [
					{
						path: 'kitchen', component: MockComponentComponent,
						data: { bc: 'look inside the kitchen' }
					},
					{
						path: 'bedroom', component: MockComponentComponent,
						data: { bc: 'look inside the bedroom' }
					}
				]
			},
			{
				path: 'guestHouse', component: MockComponentComponent,
				data: { bc: 'I\'m going in the back yard' }
			}
		]
	}
];

【讨论】:

  • 页面刷新呢?这仅在发生导航时触发,而不是在我们已经在路线上并且页面刷新时触发。
  • data 的聚合适用于页面刷新,所以我不确定你在引用什么。如果您要引用在面包屑中使用动态聚合数据的示例部分(例如示例中的 breakIns),则将它们删除是正常的,因为它们存储在内存中并在刷新时消失。例如,您可以通过将它们添加到查询参数来保留其他元素(然后您可以解析查询参数并获取过去的面包屑)。
  • 我的错。我在子模块的子组件之一中执行此操作,而不是应用程序/主模块。所以它没有听初始页面加载。它仅在该组件初始化后才侦听路由器。我想这是在主模块中执行此操作的课程。
  • @ХристиянХристов 你有这个好友的 stackblitz 吗?
  • @ХристиянХристов 感谢您的超级快速反应伙伴。让我了解您的实施。非常感谢您的努力
【解决方案2】:

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

  1. 在路由中定义面包屑的声明式方法
  2. 通过不同标签更新任何路由的动态异步方式
  3. 在面包屑中跳过特定路线的方法

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

请随意查看,开发的一个 Angular 应用程序显示了面包屑的使用 - https://xng-breadcrumb.netlify.com

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    相关资源
    最近更新 更多