首页 > 解决方案 > How I can block the access of a route to specific users

问题描述

I have some routes in my app.router.ts file:

export const ROUTES: Routes = [
    { path: 'login', component: LoginComponent },
    { path: 'home', redirectTo: '/requisicao', pathMatch: 'full' },
    { path: 'requisicao', component: PageRequisicaoComponent, canActivate: [ AuthGuard ] },
    { path: 'pacientes', component: PagePacienteComponent, canActivate: [ AuthGuard ] },
    { path: 'resultados', component: PageResultadoComponent, canActivate: [ AuthGuard ]},
    { path: 'administrativo', component: PagePainelAdministrativoComponent, canActivate: [ AuthGuard ]},
    { path: '', redirectTo: '/login', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent}
]

And I have two types of users. How I can block the access of some route for users of type 1?

@Injectable()
export class AuthGuard implements CanActivate{

    constructor(
        private router: Router
    ){}

    canActivate(): boolean{

    }
}

标签: javascriptangular

解决方案


定义路由守卫

有两种定义守卫的方法。一个更简单的方法是创建一个函数,如下所示:

// file app.routing.ts
const appRoutes: Routes = [
    {path: "", redirectTo: "board", pathMatch: "full"},
    {path: "board", component: BoardComponent, canActivate: ["boardGuard"]}
];

export const routingProviders = [
    {provide: "boardGuard", useValue: boardGuard}
];

export function boardGuard(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return true;
}
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

// file app.module.ts
import {routing, routingProviders} from "./app.routing";

@NgModule({
   import: [routing],
   providers: [routingProviders]
})
export class AppComponent {}

您还可以在保护函数中使用依赖注入,如下所示:

export const tpRoutingProviders = [
    {provide: "authenticatedGuard", useFactory: (authService: AuthService) => {
            return () => authService.isUserAuthenticated();
        },
        deps: [AuthService]
    }
];

第二个选项是定义一个实现 Can Activate 接口的类。按照这个:

// file app.routing.ts

const appRoutes: Routes = [
   {path: "worksheet", component: WorksheetComponent, canActivate: [WorksheetAccessGuard]}     
];

// file ActivationGuards.ts

@Injectable()
export class WorksheetAccessGuard implements CanActivate {
   private static USER_PARAM = "userId";

   constructor(private router: Router, private userService: CurrentUserService) {}

   public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      const currentUser = this.userService.currentUser;
      const paramUser = route.params[WorksheetAccessGuard.USER_PARAM];
      if (paramUser && paramUser !== currentUser.id && !currentUser.admin) {
          this.router.navigate(["worksheet"]);
          return false;
      }
      return true;
   }
}

// file app.module.ts

@NgModule({
   providers: [WorksheetAccessGuard]
})
export class AppComponent {}

推荐阅读