如何按角色角色仅显示当前用户的组件

问题描述

大家好,我有一个仪表板,其中包含所有组件的菜单: 我想以角色admin登录时,我想显示所有组件 如果我以负责的角色登录,我只想显示Commandes组件

我不知道要添加什么来保护我

这是我的menu.ts 从“ ./menu.model”导入{MenuItem};

export const MENU: MenuItem[] = [
  {
    label: "Navigation",isTitle: true,},{
    label: "Dashboard",icon: "home",link: "/",badge: {
      variant: "success",text: "1",{
    label: "Apps",{
    label: "Commandes",icon: "box",link: "/commandes",{
    label: "Clients",icon: "users",subItems: [
      {
        label: "Client professionelle",icon: "user",link: "/AgentPro",{
        label: "Client Particulier",link: "/clientpar",],{
    label: "Responsable Depot",icon: "eye",link: "/ResponsableDepot",];

这是我的身份验证服务:

  constructor(private http: HttpClient,private cookieService: CookieService) {}

  /**
   * Returns the current user
   */
  public currentUser(): User {
    if (!this.user) {
      this.user = JSON.parse(this.cookieService.getCookie("currentUser"));
    }
    return this.user;
  }

  /**
   * Performs the auth
   * @param email email of user
   * @param password password of user
   */
  ///api/login
  //khasni njib dak refs hna
  login(email: string,password: string) {
    return this.http
      .post<any>(` http://127.0.0.1:8000/api/login`,{ email,password })
      .pipe(
        map((user) => {
          // login successful if there s a jwt token in the response
          if (user && user.token) {
            this.user = user;

            // store user details and jwt in cookie
            this.cookieService.setCookie(
              "currentUser",JSON.stringify(user),1
            );
          }
          return user;
          console.log("this is the user infos ",user);
        })
      );
  }

  /**
   * Logout the user
   */
  logout() {
    // remove user from local storage to log user out
    this.cookieService.deleteCookie("currentUser");
    this.user = null;
  }

我的守卫:

 canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot) {
    const currentUser = this.authenticationService.currentUser();
    if (currentUser) {
      if (
        route.data.roles &&
        route.data.roles.indexOf(currentUser.roles) === -1
      ) {
        // role not authorised so redirect to home page
        this.router.navigate(["/"]);
        return false;
      }
      // logged in so return true
      return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(["/account/login"],{
      queryParams: { returnUrl: state.url },});
    return false;
  }

路由组件:

 {
    path: "",component: LayoutComponent,loadChildren: () =>
      import("./pages/pages.module").then((m) => m.PagesModule),canActivate: [AuthGuard],{
    path: "",loadChildren: () =>
      import("./components/clients-par/client.module").then(
        (m) => m.ClientModule
      ),loadChildren: () =>
      import("./components/clients-pro/clientpro.module").then(
        (m) => m.ClientproModule
      ),loadChildren: () =>
      import("./components/commandes/commandes.module").then(
        (m) => m.CommandesModule
      ),

这是我的仪表板的外观: The image

解决方法

我不知道要添加什么来保护我

如果不满足条件,则路由保护器会阻止访问特定路由。它们不会阻止显示路线链接(锚点)。

如果要隐藏路线链接,则可能需要通过* ngIf或[hidden]或其他方式来隐藏路线链接的显示。如果您的路由链接来自数组,则该数组应仅包含当前用户角色可用的路由链接。

,

尝试resolve

export class UserResolverService implements Resolve<User> {
  constructor(private service: authenticationService,private router: Router) {}

  resolve(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<User> {
    const currentUser = this.authenticationService.currentUser();
    return of(currentUser) // only if currentUser is not an observable. and this.authenticationService.currentUser() is not Asynchronous
  }
}

在每条路线中:

{
    path: "",component: LayoutComponent,loadChildren: () =>
      import("./components/commandes/commandes.module").then(
        (m) => m.CommandesModule
      ),canActivate: [AuthGuard],resolve: {user: UserResolverService}
  
  },

在每个组件中:


isShown = false;

constructor(
    private route: ActivatedRoute
  ) {}

ngOnInit() {
  this.route.data
    .subscribe((data: { user: User}) => {
      if (user === 'who') {
        isShown = true
      }
    });
}

在html中:

<div [hidden]="!isShown">
...
</div>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...