As a newcomer to TypeScript and Angular 7, I am working on implementing a feature where certain menu components are displayed based on the user's permissions (determined by JWT token role).
My approach involves using GuardServices and calling the canActivate method in a filter loop to dynamically generate the menu based on the user's roles.
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
public appPages = [
{
title: 'Dashboard',
url: '/app/dashboard',
icon: 'home'
},
{...},
{
title: 'Employees',
url: '/app/employees',
icon: 'contacts',
guard: AdminGuardService
},
{
title: 'Logout',
url: '/app/logout',
icon: 'log-out'
}
];
public authenticated = false;
public position = 'end';
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private router: Router,
private auth: AuthenticationService
) {
this.initializeApp();
}
initializeApp() {
(...)
}
getAppPages(): any {
return this.appPages.filter(page => {
if (page.guard != null) {
page.guard.prototype.auth = this.auth;
return page.guard.prototype.canActivate();
}
return true;
});
}
}
In this code snippet, I am manually injecting the authService required by the AdminGuardService. However, this method is not scalable as I may need other services with different dependencies in the future. Therefore, I would like to delegate dependency injection to Angular and simply call the canActivate() method.
@Injectable({
providedIn: 'root'
})
export class AdminGuardService implements CanActivate {
constructor(public auth: AuthenticationService) {
}
canActivate(): boolean {
return this.auth.isAuthenticated() && (this.auth.roles.includes('Admin') || this.auth.roles.includes('UserAdmin'));
}
}
Thank you!