使用canActivate确定显示链接

时间:2019-05-22 14:58:48

标签: angular

我想使用实现CanActivate的AuthGuard来确定我是否应该显示链接。但是我似乎无法获得检查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 { }

AuthGuard:

@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 here

1 个答案:

答案 0 :(得分:0)

考虑阅读CanActivate警卫队的文档。

但是主要思想if使您能够在组件加载之前并且仅在组件实现之前进行测试。

简单的例子:

CanActivate

并确保将您的路线数组编辑为

import { AuthService } from './../services/auth.service';
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {


  constructor(private _authService: AuthService, private _router: Router) {
  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this._authService.isAuthenticated()) {
        return true;
    }

    // navigate to login page
    this._router.navigate(['/login']);
    // you can save redirect url so after authing we can move them back to the page they requested
    return false;
  }

}