I have an application where I need to secure routes based on roles to a particular user. I have windows authentication in my app, so there is so separate login page for this, so I am calling login method directly from app.component.ts. Everything works fine like able to secure the routes but while refreshing the page it goes to login again where the data for roles is delayed mean while the component loads and it fails to get the roles so it is redirecting to dashboard page (as per my requirement in case any user doesn't have permissions to view a page ). I knew I have to use observables but in my case the code is a bit difference. Can any one suggest the best way to achieve this. Below is the code
app.component.ts
ngOnInit() {
this.commonService.getLogin().subscribe((data: any) => {
this.appService.roles = data.roles;
}});
app.service.ts
export class AppService {
public roles: Role[];// Array of customized class
getAccessForMenus(menuname: string) {
let hideMenu = false;
// Some code... based on some condition hide menu value will vary
return hideMenu;
}
}
can-activate-guard.ts
@Injectable()
export class CanActivateAdmin implements CanActivate {
constructor(private appService: AppService, private router: Router) { };
canActivate(){
if (!this.appService.getAccessForMenus('Admin')) {
this.router.navigateByUrl('dashboard');
}
return true;
}
}