首页 > 解决方案 > 使用 canActivate 确定显示链接

问题描述

我想使用我的 AuthGuard 实现 CanActivate 来确定我是否应该显示链接。但是我似乎无法获得检查 canActivate 的路线

我尝试创建以下功能

ts文件:

  shouldShowLink(route: Route) {
    const activate = route.canActivate;
    return activate;
  }

模板:

<li *ngIf="shouldShowLink(['account/overview'])" class="nav-item active">
    <a class="nav-link" [routerLink]="['account/overview']" routerLinkActive="active">Brugere</a>
</li>

路由:

const routes: Routes = [
  {

   path: 'account', canActivate: [AuthGuardService], data: {roles: ['Administrator']},
   children: [
     {
       path: 'create', component: CreateUserComponent,
     },
     {
       path: 'overview', component: UseroverviewComponent
     },
     {
       path: 'userinfo/:id', component: UserInfoComponent
     }
  ]
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AccountRoutingModule { }

身份验证:

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
  constructor(private router: Router, private authorizationService: AuthorizationService) { }


  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (!this.authorizationService.UserLoggedIn) {
      return false;
    }

    if (this.authorizationService.UserRole === 'EQAdministrator') {
      return true;
    }

    if (route.data.roles && route.data.roles.indexOf(this.authorizationService.UserRole) === -1) {
      return false;
    }

    return true;
  }
}

route 属性给出了一个数组,其中第一个也是唯一的条目是我通过它的路由。如果我删除数组,我只会得到一个带有路由的字符串,而不是实际的路由。

我在这里做了一个 StackBlitz

标签: angular

解决方案


目前这似乎不可能。请在 GitHub 上为相关功能请求投票


推荐阅读