1

当我在“收获前”子路径中使用RoleGuard并打开浏览器时,浏览器完全被阻止,似乎处于无限循环中。我没有任何编译问题,也无法打开控制台查看我有什么错误。

可以在子路径中使用 canActivate 吗?还是我应该使用 CanActivateChild?CanActivateChild 没有这个问题。

const preHarvestRoutes: Routes = [
  {
    path: '',
    component: PrivateComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: 'pre-harvest',
        component: PreHarvestComponent,
        canActivate: [RoleGuard],  <------- IF I REMOVE THIS I DO NOT HAVE ANY PROBLEM.
        children: [
          {
            path: 'new-field',
            component: NewFieldComponent
          },
        ]
      }
    ]
  }
];

角色守卫:

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { UserRolesService } from '../services/user-roles.service';
import { webStorage } from "../utils/web-storage";

@Injectable()
export class RoleGuard implements CanActivate    {

    constructor(
        private userRoles: UserRolesService
        , private router: Router
    ) { }

    canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot )    {
        //let roles = route.data['roles'] as Array<string>;
        //let rolesUserLogged = webStorage.user;

        this.router.navigate( ['pre-harvest'] );

        return true;
    }
}
4

1 回答 1

3

RoleGuard您正在重定向到与放置位置相同的路线。这显然会导致无限循环。您应该将您的更改RoleGuard为:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
   //let roles = route.data['roles'] as Array<string>;
   //let rolesUserLogged = webStorage.user;
   return true;
}

您仍然必须指定 RoleGuard 逻辑,但您遇到的问题是重定向到相同的路由。

于 2017-04-21T09:27:11.923 回答