我有带有面包屑的Angular 6应用,该应用来自路线数据。例如:
const routes: Routes = [
{
path: "",
component: RootComponent,
children: [
{
path: "",
data: {
breadcrumb: "products"
},
children: [
{
path: ":id",
component: ProductComponent,
data: {
breadcrumb: "product"
}
},
{
path: ":id/edit",
component: ProductEditComponent,
data: {
breadcrumb: "edit"
}
}
]
}
]
},
];
是否有办法从面包屑中的组件添加自定义信息?例如,相反products > edit
具有products > salmon > edit
。我试图从ngOnInit函数中的组件向路由添加更多数据,但问题是调用该函数时数据尚未到达,因此数据仍为undefined
。
我目前获取面包屑的逻辑类似于:
ngOnInit() {
const ROUTE_DATA_BREADCRUMB: string = "breadcrumb";
//subscribe to the NavigationEnd event
this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
//set breadcrumbs
let root: ActivatedRoute = this.activatedRoute.root;
this.breadcrumbs = this.getBreadcrumbs(root);
});
}
/**
* Returns array of IBreadcrumb objects that represent the breadcrumb
*
* @class DetailComponent
* @method getBreadcrumbs
* @param {ActivateRoute} route
* @param {string} url
* @param {IBreadcrumb[]} breadcrumbs
*/
private getBreadcrumbs(route: ActivatedRoute, url: string="", breadcrumbs: IBreadcrumb[]=[]): IBreadcrumb[] {
const ROUTE_DATA_BREADCRUMB: string = "breadcrumb";
//get the child routes
let children: ActivatedRoute[] = route.children;
//return if there are no more children
if (children.length === 0) {
return breadcrumbs;
}
//iterate over each children
for (let child of children) {
//verify primary route
if (child.outlet !== PRIMARY_OUTLET) {
continue;
}
//verify the custom data property "breadcrumb" is specified on the route
if (!child.snapshot.data.hasOwnProperty(ROUTE_DATA_BREADCRUMB)) {
return this.getBreadcrumbs(child, url, breadcrumbs);
}
//get the route's URL segment
let routeURL: string = child.snapshot.url.map(segment =>
segment.path).join("/");
//append route URL to URL
url += `/${routeURL}`;
//add breadcrumb
let breadcrumb: IBreadcrumb = {
label: child.snapshot.data[ROUTE_DATA_BREADCRUMB],
params: child.snapshot.params,
url: url
};
breadcrumbs.push(breadcrumb);
//recursive
return this.getBreadcrumbs(child, url, breadcrumbs);
}
}
答案 0 :(得分:1)
尝试在面包屑.ts中使用ngAfterViewInit。
ngAfterViewInit() {
setTimeout(()=>{
let root: ActivatedRoute = this.activeRouter.root;
//console.log(this.activeRouter.snapshot.url);
this.breadcrumbs = this.getBreadcrumbs(root);
});
}
然后在您的component.ts中,
@ViewChild(BreadcrumbComponent) breadcrumbRef: BreadcrumbComponent; //reference to the breadcrumb
ngOnInit(){
this.router.events.filter(event => event instanceof NavigationEnd).subscribe(
res => {
this.breadcrumbRef.ngAfterViewInit()
});
}