(Angular 5+) 从 child 路线获取数据
(Angular 5+) Getting data from child routes
我想为我的应用制作面包屑导航,所以我将 "title" 放在我的数据路由上,如下所示:
export const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{path: 'help', component: HelpComponent },
{
path: 'admin',
component: AdminComponent,
runGuardsAndResolvers: 'always',
data: { title: "Admin"},
canActivate: [AuthGuard],
children: [
{
path: 'organisation',
component: ListOrganizationComponent,
data:{title: "Organisation"},
resolve: {organizations: ListOrganizationResolver}
}
]
},
{ path: '**', redirectTo: 'home', pathMatch: 'full' },
];
export class AdminComponent implements OnInit {
title: string = "";
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.title = this.route.snapshot.data.title;
}
}
当我 运行 代码并转到:localhost:4200/admin/organisation
仅显示来自管理员的标题(标题 = "Admin")。我想从 child 路线获得 title Organization ..该怎么做?
有没有简单的方法在 angular 中制作面包屑?
对于你的第二个问题,我使用了 ngx-breadcrumbs
,它很容易配置,你不需要开箱即用。
npm --save install ngx-breadcrumbs
您可以在 ActivatedRoute 上使用 firstChild 属性 来检索 firstChild
路线,然后像对当前路线一样继续检索数据。这是一个例子:
export class AdminComponent implements OnInit {
breadcrumb: string;
ngOnInit() {
let breadcrumb = this.route.snapshot.data['title'];
if (this.route.snapshot.firstChild) {
breadcrumb += ' > ' + this.route.snapshot.firstChild.data['title'];
}
this.breadcrumb = breadcrumb;
}
constructor(private route: ActivatedRoute) {}
}
这是 working demo。请务必导航至 /admin/organization
.
你的第二个问题,你可以试试 ngx-breadcrumbs 另一个答案提到的。
我想为我的应用制作面包屑导航,所以我将 "title" 放在我的数据路由上,如下所示:
export const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{path: 'help', component: HelpComponent },
{
path: 'admin',
component: AdminComponent,
runGuardsAndResolvers: 'always',
data: { title: "Admin"},
canActivate: [AuthGuard],
children: [
{
path: 'organisation',
component: ListOrganizationComponent,
data:{title: "Organisation"},
resolve: {organizations: ListOrganizationResolver}
}
]
},
{ path: '**', redirectTo: 'home', pathMatch: 'full' },
];
export class AdminComponent implements OnInit {
title: string = "";
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.title = this.route.snapshot.data.title;
}
}
当我 运行 代码并转到:localhost:4200/admin/organisation
仅显示来自管理员的标题(标题 = "Admin")。我想从 child 路线获得 title Organization ..该怎么做?
有没有简单的方法在 angular 中制作面包屑?
对于你的第二个问题,我使用了 ngx-breadcrumbs
,它很容易配置,你不需要开箱即用。
npm --save install ngx-breadcrumbs
您可以在 ActivatedRoute 上使用 firstChild 属性 来检索 firstChild
路线,然后像对当前路线一样继续检索数据。这是一个例子:
export class AdminComponent implements OnInit {
breadcrumb: string;
ngOnInit() {
let breadcrumb = this.route.snapshot.data['title'];
if (this.route.snapshot.firstChild) {
breadcrumb += ' > ' + this.route.snapshot.firstChild.data['title'];
}
this.breadcrumb = breadcrumb;
}
constructor(private route: ActivatedRoute) {}
}
这是 working demo。请务必导航至 /admin/organization
.
你的第二个问题,你可以试试 ngx-breadcrumbs 另一个答案提到的。