如何通过保护angular2隐藏链接 [英] How to hide link by guard angular2

查看:24
本文介绍了如何通过保护angular2隐藏链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在视图 html 中隐藏管理链接.我要守着:管理员和经理

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

路由器配置:

{
   path: 'manager',
   component: ManagerComponent,
   canActivate: [ManagerGuard]
},
{
   path: 'user',
   component: UserAdminComponent,
   canActivate: [AdminGuard]
}

在视图中:

 <li>
    <a routerLink="/user" routerLinkActive="active-link">User</a>
 </li>

我想在/user 上为 ManagerGuard 隐藏链接,但为 AdminGuard 显示.

I want to hide link on /user for ManagerGuard when but show for AdminGuard.

推荐答案

此外,如果已经以可能有用的方式回答了问题,我在这里使用了另一种方法.由于您已经在 Guard 中拥有您的 canActivate 方法,您还可以使用该 Guards 注入您的导航组件,您可以直接调用这些 canActivate 方法:

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:

在包含导航的组件中

constructor(private adminGuard: AdminGuard)

然后在模板中

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

编辑

在我的情况下,这在 prod 模式下不起作用(如果您使用必须注入的参数).我只是试图编译它,但 angular 抱怨缺少参数.如果您不使用参数,这可以正常工作,或者,如果您不在函数中使用参数 - 则只需传递

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>

另一件事:如果你是模板中的adminGuard"这样的变量,它必须是公共的——而不是私有的.

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

这篇关于如何通过保护angular2隐藏链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆