Search code examples
angularangular2-routingrolesangular-router-guardsangular-guards

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


Hello every one i have a dashboard that has a menu of all the components : i want when i m logged in with the role admin i want to display all the components and if i m logged with the responsable role i want to show just the commandes component

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

this is my menu.ts import { MenuItem } from "./menu.model";

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",
  },];

this is my auth service :

  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;
  }

My guard :

 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;
  }

Routing component :

 {
    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],
  
  },

this is how my dashboard looks like : The image


Solution

  • try 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
      }
    }
    

    in each route:

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

    in each component:

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

    in html:

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