Angular useFactory to provide a canActivate Service
Mon Feb 20 2023 10:57:06 GMT+0000 (Coordinated Universal Time)
Saved by
@mtommasi
example:
I have a canActivate guard that can have different roles, for this use case i can use a provider factory:
1- use an injection token (or a string) : 'AdminRoleGuard'
2- inside the can activate guard of the path use this string
{path:'Admin',canActivate:['AdminRoleGuard']}
3- inside the app.module.ts create the provider factory:
useFactory prende come input tutti i dependency di cui ha bisogno il service
NgModule({
providers:[
{provide:'AdminRoleGuard',
useFactory:(router:Router,authorizationService:AuthorizationService)=>{
return new RoleGuard(['admin'],router,authorizationService)
},
deps:[Router,AuthorizationService]
}
]
})
---
the guard needs a factory to be instantiated
@Injectable()
class RoleGuard implements CanActivate {
constructor(roles:[],router:Router,authService:AuthService){}
canActivate(activatedRouteSnapshot,routerStateSnapshot){
....
}
}
content_copyCOPY
Comments