问题描述
是否有一种方法可以实现基于导航历史的面包屑,而不是基于常规路线路径的面包屑.
Is there a way to implement navigation history based breadcrumb instead of normal route path based breadcrumb.
示例路线 :主页-HChild1-HChild1.1主页-HChild2-HChild2.1
exampleRoute :Home - HChild1 - HChild1.1Home - HChild2 - HChild2.1
如果用户从主页导航至HChild2.1,则面包屑应为设为首页HChild2.1
If user navigates to HChild2.1 from Home page breadcrumb should beHome | HChild2.1
而不是设为首页HChild2 | HChild2.1
instead ofHome | HChild2 | HChild2.1
然后,如果用户从HChild2.1导航到HChild1.1,则面包屑应为设为首页HChild2.1 | HChild1.1
Then if user navigates to HChild1.1 from HChild2.1 then breadcrumb should beHome | HChild2.1 | HChild1.1
而不是设为首页HChild1.1 | HChild1.1
instead ofHome | HChild1.1 | HChild1.1
我所拥有的是基于常规路由路径的面包屑,因为我只能导航到Paranet组件,而不能导航到上一个组件,所以这没有用.
what I have is normal route path based breadcrumb which doesn't serve my purpose as I can only navigate to the paranet component but not to the previous component.
谢谢
推荐答案
使用面包屑组件填充导航结束路线中的最后一条路线.
Use breadcrumb component to populate last route in navigation end route.
路线必须具有面包屑数据
route must have breadcrumb data
//Home route
{
path: '',
component: HomeComponent,
data: {breadcrumb:'Home'},
}
这是我制作的面包屑成分.
Here is the breadcrumb component I made.
export interface BreadCrumb {
label: string;
url: string;
};
@Component({
selector: 'breadcrumb',
template: `<span *ngFor="let breadcrumb of breadcrumbs" >
<a [routerLink]="breadcrumb.url">
{{ breadcrumb.label }}
</a>|
</span>`
})
export class BreadCrumbComponent {
private history = [];
breadcrumbs: BreadCrumb[] = [];
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
) { }
public ngOnInit(): void {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd), distinctUntilChanged(),map(() => {
return this.buildBreadCrumb(this.activatedRoute.root)
}
))
.subscribe(event => {
this.breadcrumbs.push(event);
console.log(this.breadcrumbs)
});
}
buildBreadCrumb(route: ActivatedRoute, url: string = ''): BreadCrumb {
const label = route.routeConfig ? route.routeConfig.data['breadcrumb'] : 'Home';
const path = route.routeConfig ? `/${route.routeConfig.path}` : '';
const nextUrl = `${url}${path}`;
const breadcrumb = {
label: label,
url: nextUrl
};
if (route.firstChild) {
return this.buildBreadCrumb(route.firstChild, nextUrl);
}
return breadcrumb;
}
}
这篇关于基于导航历史记录而不是路线路径的角面包屑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!