In my Angular8 app, there are 2 dashboard pages for User and Admin and I want to load the corresponding dashboard by using the role of a user to the PanelComponent. I think to use ngIf
in the PanelComponent.html and load the corresponding dashboard according to role, but not sure if this is a good idea or not :(
On the other hand, there are some questions about that like How to achieve Role Based redirection after login in Angular-5?, but there is not a good example about that. So, what is the best way to implement this approach?
Angular Route Guards is the best practise in order to support role based access. However if you want to support role based access for only two pages and the requirements will not expand in time then I do not see anything wrong with using ngIf. I would go that way in such a case.
If you want to use route guards anyway, then you should implement CanActivate interface accordingly. It is going to be your route guard implementation. This class is responsible of showing or not showing the requested page depending on the role. If the user does not have the required role then it redirects to a http 404 or 403 page you had created.
import { Injectable } from '@angular/core';
import {
Router,
CanActivate,
ActivatedRouteSnapshot
} from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class RouteGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {
}
canActivate(route: ActivatedRouteSnapshot): boolean {
if (
!this.auth.isAuthorized(route.data.roleCode)
) {
this.router.navigate(NotFoundPage.PATH);
return false;
}
return true;
}
}
You can set your route's role group in your app-routing.module as below
export const ROUTES: Routes = [
{
path: 'admin',
component: AdminDashBoardComponent,
canActivate: [RouteGuardService],
data: {
roleCode: 'admin'
}
},
{
path: 'user',
component: UserDashBoardComponent,
canActivate: [RouteGuardService],
data: {
roleCode: 'user'
}
},
{
path: 'other',
component: OtherPageComponent,
canActivate: [RouteGuardService],
data: {
roleCode: 'user'
}
},
{ path: '**', redirectTo: '' }
];
I did not share the Authentication service for brevity what it can do is simply comparing the roleCode of user and route.data.roleCode. You can also integrate your authentication logic into this RouteGuardService if user is not logged in you can redirect it to loginpage again.
All of this was to prevent unauthorized access to your pages.
Your requirement as to redirecting to the correct page after login sounds like you want a dynamic home page. Redirecting depending on role group right after login would not be a good practise.
You can redirect in your Home Page Component's ngOnInit instead. This provides a better design.
export class HomePageComponent {
...
ngOnInit() {
if (this.auth.isAuthorized('admin')) {
this.router.navigateByUrl('/admin');
} else if (this.auth.isAuthorized('user')) {
this.router.navigateByUrl('/user');
}
}