When the user load the app, the server checks if he is allowed to access it. If not, I would like to redirect it to an error page.
Relevant code from index.html I
<app-root></app-root>
main.ts
platformBrowserDynamic().bootstrapModule(AppModule)
The AppModule includes inside it the routes for the lazy load modules, and when I try to access an url, it begin to build the routes although I am not authorized.
The authorization check occurs here:
app.module.ts
@NgModule({
...
providers:[
{
provide: APP_INITIALIZER,
**useFactory: startupServiceFactory,**
...
}
]
**startupServiceFactory**(){
return () => startupService.load();
}
Could I redirect the user to an error page ?
You can simply make check using canActivate
of Angular like this -
{
path: '',
component: yourComponent,
canActivate: [ AuthGuardService ]
}
Here AuthGuardService
is your service where you can check whether user is authorized or not and redirect accordingly.
I am prefare to make this in backend ... if is authenticated : I am calling this view " " if not : calling another view
and you can make this solution on the same page
$(document).ready(function(){ if ( true) { document.getElementById("main").innerHTML = "<AppRoot>Loading ...</AppRoot>"; } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> aaaaaa</div> <div id="main"> </div>
If you want make permissions on angular routes you can add
{
path: 'abc',
component: abcComponent,
canActivate: [ AuthGuard ],
data: {
roles: ['admin'] ,
},
{ path: '**', component: PageNotFoundComponent }
}
and type your code of AuthGuard As you want:
@Injectable()
export class AuthGuard implements CanActivate {
constructor( private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
// let roles = route.data["roles"] as Array<string>;
if (role Condition)
return true;
else
{
this.router.navigateByUrl("/notfound");
//return false;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.