首页 > 解决方案 > 检查对页面的访问

问题描述

我需要创建一个方法来检查数据访问是否等于 next.data.access。我可以使用包含方法,因为它是一个数组。数组中只有一个数据访问值可以返回 true

auth.guards.ts

 canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return from(this.authService.me().then(data => {
      let access = data['role']['unlocks'];
      if('access' in next.data) {
        let eachAccess = next.data.access.forEach(each => {
          each.includes(access);
        } );
        let hasAccess = eachAccess === next.data.access;
        console.log(hasAccess)
        if (hasAccess) {
          return next.component !== LoginComponent;
        } else {
          console.warn('User doesn\'t have access to this page.');
          this.router.navigate(['/selection']);
          return false;
        }

路由模块.ts

  { path: 'admin', canActivate:[AuthGuard], component: AdminComponent, data: {access : ['ALL']}, children: [
      { path: 'manageUsers', component: ManageUserComponent}
    ]},

  { path: 'client', canActivate:[AuthGuard], data: {access : ['ALL','CLIENT']}, children: [
      { path: '', component: DashboardComponent },
      { path: 'dashboard', component: DashboardComponent},
      { path: 'greenhouse', component: GreenhouseComponent},
      { path: 'recipe', component: RecipeComponent},
      { path: 'greenhouse/mylamps', component: MylampsComponent},
    ]},

  { path: 'tools', canActivate:[AuthGuard], data: {access : ['ALL','TOOLS']}, children: [
    { path: '', component: ToolsComponent },
    { path: 'information', component: UserInformationComponent},
    { path: 'light', component: LightComponent},
    { path: 'spectrum', component: RefSpectrumComponent},
    { path: 'test', component: TestComponent},
    { path: 'progress', component: InProgressComponent}
  ]},

标签: javascriptangular

解决方案


为此,您不能使用forEach它,因为它不会返回任何东西。

const arr = arr = [1, 2, 3];
const res = arr.forEach(v => v *2);

console.log(res); // undefined

您可以改用Array.prototype.includes()

const hasAccess = next.data.access.includes(access);

或者,如果您想搜索更复杂的内容,可以使用Array.prototype.some()

const hasAccess = next.data.access.includes(acc => acc === access);

推荐阅读