要动态更改面包屑,您需要使用AsyncPipe以异步方式从Observable获取路由事件。以下是一个代码示例:
在组件类中:
import { Component } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { filter, map } from 'rxjs/operators';
import { MenuItem } from 'primeng/api';
@Component({
selector: 'app-breadcrumb',
templateUrl: './breadcrumb.component.html',
styleUrls: ['./breadcrumb.component.css']
})
export class BreadcrumbComponent {
items: MenuItem[];
constructor(private router: Router, private activatedRoute: ActivatedRoute) {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map(route => {
while (route.firstChild) route = route.firstChild;
return route;
}),
filter(route => route.outlet === 'primary'),
mergeMap(route => route.data),
map(data => {
if (data.title) {
// If there is a breadcrumb override, use that instead of the title
if(typeof data.title === 'function') {
return data.title(this.activatedRoute.snapshot.params);
}
return data.title;
} else {
return null;
}
})
).subscribe((label: string) => {
if (label) {
this.items.push({label: label});
}
});
}
ngOnInit() {
this.items = [];
}
}
在组件模板中:
注意:确保已正确导入并安装了Primeng和rxjs模块。