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

how to show just the components of the current user by role in angular

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

我不知道要在我的警卫中添加什么才能做到这一点

这是我的 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",
    isTitle: true,
  },

  {
    label: "Commandes",
    icon: "box",
    link: "/commandes",
  },
  {
    label: "Clients",
    icon: "users",
    subItems: [
      {
        label: "Client professionelle",
        icon: "user",
        link: "/AgentPro",
      },
      {
        label: "Client Particulier",
        icon: "user",
        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: "",
    component: LayoutComponent,
    loadChildren: () =>
      import("./components/clients-par/client.module").then(
        (m) => m.ClientModule
      ),
    canActivate: [AuthGuard],
  },
  {
    path: "",
    component: LayoutComponent,
    loadChildren: () =>
      import("./components/clients-pro/clientpro.module").then(
        (m) => m.ClientproModule
      ),
    canActivate: [AuthGuard],
  },
  {
    path: "",
    component: LayoutComponent,
    loadChildren: () =>
      import("./components/commandes/commandes.module").then(
        (m) => m.CommandesModule
      ),
    canActivate: [AuthGuard],
  
  },

这是我的仪表板的样子: The image

i don t know what to add in my guard to do this

如果不满足条件,路由守卫会阻止访问特定路由。它们不会阻止路由链接(锚点)的显示。

如果您试图隐藏路由链接,则需要通过 *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>