How to hide link by guard angular2

前端 未结 2 2049
我寻月下人不归
我寻月下人不归 2021-02-08 10:45

How to hide admin link in view html. I have to guard :Admin and Manager

Router config :

{
   path: \'manager\',
   component: ManagerComponent,
   canAct         


        
相关标签:
2条回答
  • 2021-02-08 11:21

    Also if already answered in a way which might be helpful, I used here another approach. As you already have your canActivate method in the Guard, you could also inject your navigation component with that Guards and you can call these canActivate methods directly:

    In your component which holds the navigation

    constructor(private adminGuard: AdminGuard)
    

    and then in the template

    <li *ngIf="adminGuard.canActivate()">
      <a routerLink="/user" routerLinkActive="active-link">User</a>
    </li>
    

    Edit

    This does not work in prod mode in my case (if you use parameters which have to be injected). I just tried to compile it but angular complains about the missing parameters. If you do not use parameters, this works fine, or, if you do not use the parameters in your function - then simply pass

    <li *ngIf="adminGuard.canActivate(null,null)">
      <a routerLink="/user" routerLinkActive="active-link">User</a>
    </li>
    

    Another thing: If you is variables like the 'adminGuard' above in the template, it must be public - not private.

    0 讨论(0)
  • 2021-02-08 11:42

    In my opinion this has nothing to do with the router itself.

    Your Guards may call another service which has the information about which kind of user is logged in: Admin or Manager.

    You should create a service that knows the type of the user. Then inject this service with Dependency Injection into your component where you have the routerLink.

    There you can ask the service and toggle the link with *ngIf:

    <li *ngIf="myService.getCurrentUser().isAdmin()">
        <a routerLink="/user" routerLinkActive="active-link">User</a>
    </li>
    

    So the service provides a function that gives you the user which is currently logged in and the isAdmin()-function of the user returns true or false. If the user is admin then the <li> will be shown, otherwise it will be hidden.

    This is just an example but I hope you get the point. It has more to do with basic functionality of Angular 2 rather than the router of Angular 2. More information about *ngIf can be found here.

    0 讨论(0)
提交回复
热议问题