我已使用以下代码在我的angular 7应用程序中实现了面包屑 Breadcrumbs.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute, PRIMARY_OUTLET } from '@angular/router';
import { filter, map } from 'rxjs/operators';
@Component({
selector: 'blm-bread-crumbs',
templateUrl: './bread-crumbs.component.html',
styleUrls: ['./bread-crumbs.component.scss']
})
export class BreadCrumbsComponent implements OnInit {
breadcrumbs: any = [];
constructor(private router: Router, private activatedRoute: ActivatedRoute) { }
ngOnInit() {
debugger
this.router.events
.pipe(filter((event: any) => 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 => {
// debugger
let snapshot = this.router.routerState.snapshot;
this.breadcrumbs = [];
let url = snapshot.url;
let routeData = route.snapshot.data;
console.log(routeData);
routeData.breadcrumb.forEach((item: any) => {
// console.log(item);
this.breadcrumbs.push({
url: item.url,
label: item.label,
terminalOnly: item.terminalOnly
});
});
});
}
renderRoute(data: any) {
if (data.url) {
this.router.navigate([data.url]);
}
}
}
下面是我的Breadcrumbs.component.html
<div class="breadcrum">
<span *ngFor="let data of breadcrumbs">
<a (click)="renderRoute(data)">
{{data.label}}</a><span *ngIf="!data.terminalOnly">>></span>
</span>
</div>
我的问题是重新加载/刷新页面后,面包屑未加载/消失。 而且当我第一次登录时,面包屑也没有显示
请帮助我提前解决问题
答案 0 :(得分:1)
我的应用程序具有相同的功能,但是mine works correctly。如果可能的话,下面是代码:
export class RouteBreadcrumbsComponent {
breadcrumbs = [];
constructor(
private router: Router,
) {
let buffer = [];
/*
Listen for router events in reverse order (to get all events).
From the snapshots, return its path and its breadcrumb.
*/
this.router.events.pipe(
filter(event => event instanceof ActivationEnd),
map((event: ActivationEnd) => [
event.snapshot.data && event.snapshot.data.crumb || undefined,
this.determineCorrectPath(event.snapshot),
]),
filter(([crumb, url]) => !!crumb),
).subscribe(([crumb, url]) => buffer.push({ crumb, url }));
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe(event => {
this.breadcrumbs = buffer.reverse();
buffer = [];
});
}
determineCorrectPath(snapshot: ActivatedRouteSnapshot) {
const path = snapshot.routeConfig.path;
const params = snapshot.params;
// Path = route with a param, so get the param
if (path.startsWith(':'))
return params[path.replace(':', '')];
// Path = '' = route group or root route of a lazy loaded module, so take the parent path
else if (!path)
return snapshot.parent.routeConfig.path;
// Path can be used as is
else
return path;
}
buildRoutingArray(crumbIndex: number) {
return this.breadcrumbs
.slice(0, crumbIndex + 1)
.map(crumb => crumb.url)
.join('/');
}
}
答案 1 :(得分:0)
我遇到了同样的问题。尝试将事件处理从 onInit 移至构造函数,生命周期挂钩中可能会错过路由事件。