我有一个使用 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
and RouterStateSnapshot
。有没有办法相对于目标路线进行导航(在这种情况下为 categoryA)?任何帮助将不胜感激。
笔记:
- 除了添加一些路由保护之外,我无法更改路由配置。
- 我不是在寻找
this.router.navigateByUrl
使用state.url
. 我想用router.navigate([...], { relativeTo: this-is-what-need})
.