Angular:如何相对于RouteGuard中的目标路由调用router.navigate()?

时间:2018-04-12 22:02:30

标签: angular angular-routing angular-route-guards

我有一个使用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个对象,而我只有ActivatedRouteSnapshotRouterStateSnapshot。有没有办法相对于目标路线导航(在这种情况下 categoryA )?任何帮助将非常感激。

注意:

  • 除了添加一些路线保护之外,我无法更改路线配置。
  • 我不希望使用this.router.navigateByUrl寻找state.url。我想使用router.navigate([...], { relativeTo: this-is-what-need})

2 个答案:

答案 0 :(得分:1)

如果你在/ product / CategoryA,你可以使用相对导航,你想导航到/ product / CategoryB:

this.router.navigate([ '../CategoryB' ], { relativeTo: this.route });

答案 1 :(得分:1)

事实证明,注入ActivatedRoute的构造函数在 RouteGuard 中的工作方式与 Component 等其他地方的工作方式不同。

在组件中,ActivatedRoute对象指向激活该组件的路由。例如,在CategoryAComponent类中,以下代码将导航到 CategoryB

this.router.navigate([ '../CategoryB' ], { relativeTo: this.route });

但是,上面的相同代码不适用于添加到 CategoryA 路由配置的RouteGuard类。在我的测试中,我发现构造函数注入了ActivatedRoute个对象指向根路径。另一方面,ActivatedRouteSnapshot对象(作为 canActivate 函数中的参数传入)指向目标路径(在我的情况下为 categoryA )。但是,我们无法在ActivatedRouteSnapshot函数中传递此this.router.navigate(...)对象。

我无法找到解决此问题的更好方法,但以下代码对我有用:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    return this.myService.checkPermission()
        .then(result => {
            if (!result.hasAccess) {
                //redirect here

                let redirectTo = route.pathFromRoot
                    .filter(p => p !== route && p.url !== null && p.url.length > 0)
                    .reduce((arr, p) => arr.concat(p.url.map(u => u.path)), new Array<string>());

                this.router.navigate(redirectTo.concat('categoryB'), { relativeTo: this.route });
            }
            return result.hasAccess;
        });
}