Angular 2 得到 parent 激活的路线
Angular 2 get parent activated route
我有一条路线 children 是这样的:
{
path: 'dashboard',
children: [{
path: '',
canActivate: [CanActivateAuthGuard],
component: DashboardComponent
}, {
path: 'wage-types',
component: WageTypesComponent
}]
}
在浏览器中,我想获得激活的 parent 路由,例如
host.com/dashboard/wage-types
如何获得 /dashboard
但可以使用 Angular 2 而不是 JavaScript,而且我也可以接受 JavaScript 代码但主要 Angular 2.
您可以通过在 ActivatedRoute 上使用父 属性 来做到这一点 - 就像这样。
export class MyComponent implement OnInit {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.parent.url.subscribe((urlPath) => {
const url = urlPath[urlPath.length - 1].path;
})
}
}
您可以在此处更详细地查看 ActivatedRoute 中的所有内容:
https://angular.io/api/router/ActivatedRoute
您可以通过确定其中是否只有一个斜线来检查父路由:
constructor(private router: Router) {}
ngOnInit() {
this.router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe((x: any) => {
if (this.isParentComponentRoute(x.url)) {
// logic if parent main/parent route
}
});
}
isParentComponentRoute(url: string): boolean {
return (
url
.split('')
.reduce((acc: number, curr: string) => (curr.indexOf('/') > -1 ? acc + 1 : acc), 0) === 1
);
}
我有一条路线 children 是这样的:
{
path: 'dashboard',
children: [{
path: '',
canActivate: [CanActivateAuthGuard],
component: DashboardComponent
}, {
path: 'wage-types',
component: WageTypesComponent
}]
}
在浏览器中,我想获得激活的 parent 路由,例如
host.com/dashboard/wage-types
如何获得 /dashboard
但可以使用 Angular 2 而不是 JavaScript,而且我也可以接受 JavaScript 代码但主要 Angular 2.
您可以通过在 ActivatedRoute 上使用父 属性 来做到这一点 - 就像这样。
export class MyComponent implement OnInit {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.parent.url.subscribe((urlPath) => {
const url = urlPath[urlPath.length - 1].path;
})
}
}
您可以在此处更详细地查看 ActivatedRoute 中的所有内容: https://angular.io/api/router/ActivatedRoute
您可以通过确定其中是否只有一个斜线来检查父路由:
constructor(private router: Router) {}
ngOnInit() {
this.router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe((x: any) => {
if (this.isParentComponentRoute(x.url)) {
// logic if parent main/parent route
}
});
}
isParentComponentRoute(url: string): boolean {
return (
url
.split('')
.reduce((acc: number, curr: string) => (curr.indexOf('/') > -1 ? acc + 1 : acc), 0) === 1
);
}