【发布时间】:2018-09-23 04:43:48
【问题描述】:
我有一个使用 Angular 4 开发的现有项目。我需要根据用户权限控制对特定路由的访问。简化的路由配置如下所示:
[
{ path: '', redirectTo: '/myApp/home(secondary:xyz)', pathMatch: 'full' },
{ path: 'myApp'
children: [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', ... },
...
{ path: 'product'
children: [
{ path: '', redirectTo: 'categoryA', pathMatch: 'full' },
{ path: 'categoryA', component: CategoryAComponent, canActivate: [CategoryACanActivateGuard]},
{ path: 'categoryB', component: CategoryBComponent},
...
]
},
...
]
},
...
]
现在,我想控制对www.myWeb.com/myApp/product/categoryA 的访问。如果用户没有足够的权限,他/她将被重定向到... /product/CategoryB。我写了一个CanActivate RouteGuard 来做这个,守卫类看起来像这样:
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, ActivatedRoute } from '@angular/router';
import { MyService } from '... my-service.service';
@Injectable()
export class CategoryACanActivateGuard implements CanActivate {
constructor(private myService: MyService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
return this.myService.checkPermission()
.then(result => {
if (!result.hasAccess) {
//redirect here
this.router.navigate(['./myApp/product/categoryB']);
//works, but I want to remove hardcoding 'myApp'
//this.router.navigate(['../../categoryB']);
//doesn't work, redirects to home page
//this.router.navigate(['./categoryB'], { relativeTo: this.route});
//do not have this.route object. Injecting Activated route in the constructor did not solve the problem
}
return result.hasAccess;
});
}
}
一切正常,但我希望相对于目标路由进行重定向,如下所示:
this.router.navigate(['/product/categoryB'], { relativeTo: <route-of-categoryA>});
// or
this.router.navigate(['/categoryB'], { relativeTo: <route-of-categoryA>});
不幸的是,relativeTo 只接受ActivatedRoute 对象,而我只有ActivatedRouteSnapshot 和RouterStateSnapshot。有没有办法相对于目标路线进行导航(在本例中为 categoryA)?任何帮助将不胜感激。
注意:
- 除了添加一些路由保护之外,我无法更改路由配置。
- 我不是使用
state.url寻找this.router.navigateByUrl。我想使用router.navigate([...], { relativeTo: this-is-what-need})。
【问题讨论】:
标签: angular angular-routing angular-route-guards