1

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

2 Answers2

0

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

Route guards prevent accessing a particular route if conditions are not met. They will not prevent the display of route links(anchors).

If you are trying to hide the route links, you will need to hide the display of the route links through maybe *ngIf or [hidden] or some other way. If your route links are coming from an array, the array should only contain route links that are available to the current user role.

Kunal Karmakar
  • 573
  • 7
  • 12
  • So do i need to do for each user an array of the components that i want to show in that case i have 3 so i need to do three menu.ts – II-ZIAD- II Sep 11 '20 at 04:56
  • For each user, based on the user's roles, you can generate the array of route links that are supposed to be accessible by the user, so that, user only gets the option to select one of the route links available to him. And on clicking the route link, the respective component is opened. – Kunal Karmakar Sep 11 '20 at 05:07
0

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>
Liem
  • 446
  • 1
  • 6
  • 20