【问题标题】:how to show just the components of the current user by role in angular如何通过角度角色仅显示当前用户的组件
【发布时间】:2020-09-11 11:12:00
【问题描述】:

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

我不知道在我的后卫中添加什么来做到这一点

这是我的 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

【问题讨论】:

    标签: angular angular2-routing roles angular-router-guards angular-guards


    【解决方案1】:

    试试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>
    

    【讨论】:

      【解决方案2】:

      我不知道在我的后卫中添加什么来做到这一点

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

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

      【讨论】:

      • 所以我需要为每个用户做一个我想要显示的组件数组,在这种情况下我有 3 个所以我需要做三个 menu.ts
      • 对于每个用户,根据用户的角色,您可以生成用户应该可以访问的路由链接数组,这样,用户只能选择一个路由他可用的链接。在点击路由链接时,相应的组件就会打开。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      相关资源
      最近更新 更多