2

我有一个应用程序,我需要根据角色保护特定用户的路由。我的应用程序中有 Windows 身份验证,因此有单独的登录页面,所以我直接从 app.component.ts 调用登录方法。一切正常,就像能够保护路由一样,但是在刷新页面时它会再次登录,其中角色的数据被延迟意味着在组件加载并且无法获取角色时,它会重定向到仪表板页面(根据我的要求以防任何用户无权查看页面)。我知道我必须使用 observables,但就我而言,代码有点不同。任何人都可以提出实现这一目标的最佳方法。下面是代码

app.component.ts

ngOnInit() {
  this.commonService.getLogin().subscribe((data: any) => {
    this.appService.roles = data.roles;
  }});

应用服务.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;
  }
}

可以激活-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;
 }
}
4

0 回答 0