我的app.router.ts文件中有一些路由:
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}
]
我有两种类型的用户。 如何阻止类型1的用户访问某些路由?
@Injectable()
export class AuthGuard implements CanActivate{
constructor(
private router: Router
){}
canActivate(): boolean{
}
}
答案 0 :(得分:0)
您基本上需要某种机制来获取用户类型。
然后,您可以根据用户类型轻松返回SceneKit
或true
。
false
答案 1 :(得分:0)
定义路线守卫
有两种定义防护的方法。一个简单的方法就是通过创建一个函数,如下所示:
// 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 {}