0

Angular2 路由中的守卫按照它们提供的顺序运行。但是对于带有 observable 的守卫,即使第一个守卫为真,angular 也会忽略它,并且只应用第二个守卫的 observable 的结果。

我该如何解决这个问题?

const mainRoutes: Routes = [
  {
  path: 'app',
  component:MainComponent,
  canActivate:[AuthGuard],
  children:[
     { path: 'dashboard',  component: DashboardComponent },
     { path: 'protectedRoute',  component: ProtectedRouteComponent, canActivate:[Admin1Guard,Admin2Guard] }
  ]}
];

第一后卫:

canActivate() :Observable<boolean>{
    return this.authService.getUser().map(res=>{
        if(res.user.role=="admin1")
          return true;
      }).take(1);
   }
 }

第二后卫:

canActivate() :Observable<boolean>{
    return this.authService.getUser().map(res=>{
        if(res.user.role=="admin2")
          return true;
      }).take(1);
    }
  }
4

1 回答 1

2

我会将角色检查逻辑重构为单个通用 服务,并通过属性CheckRoleGuard附加角色名称以检查路由:data

{
  path: 'protectedRoute1',
  component: SomeComponent,
  canActivate: [CheckRoleGuard],
  data: { allowedRoles: ['admin','editor'] }
},
{
  path: 'protectedRoute2',
  component: SomeComponent,
  canActivate: [CheckRoleGuard],
  data: { allowedRoles: ['admin'] }
}

现在对于RoleGuard服务:

@Injectable()
class CheckRoleGuard {

  constructor(private authService: AuthService) { }

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    // Retrieve the allowed roles from `route.data`.
    const allowedRoles = route.data['allowedRoles'];

    return this.authService.getUser()
      .map(data => {
        return allowedRoles.indexOf(data.user.role) !== -1;
      });
  }

}
于 2017-02-13T19:04:37.633 回答