如何禁用用户通过angular2+中的url访问页面/角4

如何禁用用户通过angular2+中的url访问页面/角4,angular,typescript,authentication,Angular,Typescript,Authentication,我必须为只有指定用户才能访问按钮的用户设置身份验证,因为我使用了localStorage,这样,当除admin之外的任何用户尝试访问按钮时,我都会隐藏该按钮 但用户也可以通过以下链接访问按钮: http://localhost:4200/#/master-system/add-user 或 因此,为了禁用该子项(我猜是该子项,如果我错了,请纠正我),我在authguard.ts文件中添加了canActivateChild,并在app.routing.ts文件中添加了一些更改,但它不起作用 另外

我必须为只有指定用户才能访问按钮的用户设置身份验证,因为我使用了localStorage,这样,当除admin之外的任何用户尝试访问按钮时,我都会隐藏该按钮

但用户也可以通过以下链接访问按钮:

http://localhost:4200/#/master-system/add-user

因此,为了禁用该子项(我猜是该子项,如果我错了,请纠正我),我在authguard.ts文件中添加了canActivateChild,并在app.routing.ts文件中添加了一些更改,但它不起作用

另外,我有许多routing.ts文件。我在主系统中有5个组件,这个主系统有自己的routing.ts文件,这个master-system.routing.ts文件包含在主routing.ts文件中。因此,当不是管理员用户时,必须停用该子用户

authguard.ts

  import { Injectable } from '@angular/core';
   import { Router, CanActivate, ActivatedRouteSnapshot,          
 RouterStateSnapshot, CanActivateChild } from '@angular/router';


  @Injectable()


    export class AuthGuard implements CanActivateChild, CanActivate {
    expectedRole: any;
    accessId:boolean=false;
    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)           
       {
    if (localStorage.getItem('CurrentUser')) {

        console.log("IN AUTHGUARD", localStorage.getItem('CurrentUser'));
        console.log("inside CanActivate - true  ")
        return true;

      }
      else {

        this.router.navigate(['/pages/login'], { queryParams: { returnUrl:       

      state.url } });
        console.log("inside CanActivate - false -  

       this.router.navigate(['/pages/login'] ")
        return false;
          }
       }

     canActivateChild(route: ActivatedRouteSnapshot, state:            
     RouterStateSnapshot) {
     this.expectedRole = route.data;

        if ( localStorage.getItem('Access') == "18") {

              this.accessId = true;
              localStorage.setItem('accessId',            
      JSON.stringify(this.accessId));
              var output = localStorage.getItem('accessId');
              console.log("localStorage.getItem('accessId') = ",output)

             return true;
        }

        else 

        {
            this.router.navigate(['/pages/login'], { queryParams: {         
       returnUrl: state.url } });

            return false;            }

     }
     }
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import{ AuthGuard } from '.././authguard/authguard';
    import { MasterSystemsComponent } from './master-systems/master-   
   systems.component';
    import { AddSystemComponent } from './add-system/add-  
     system.component';
     import { UpdateSystemComponent } from './update-system/update- 
     system.component';



   const routes: Routes = [
    {
       path: '',
       data: {
        title: 'Master System'
       },
       children: [
        {
            path: 'master-systems',
            component: MasterSystemsComponent,
            data: {
                title: 'Master Systems'
            }
          },
          {
            path: 'master-interface',
            component: MasterInterfaceComponent,
            data: {
                title: 'Master Interface'
            }
        },
        {
            path: 'master-user',
            component: MasterUserComponent,
            data: {
                title: 'Master User'
            }
        },
        {
            path: 'master-group',
            component: GroupComponent,
            data: {
                title: 'Master Group'
            }
        },
        {
            path: 'master-role',
            component: RoleComponent,
            data: {
                title: 'Master Role'
            }
        },
        {
            path: 'add-system',
            component: AddSystemComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-system',
            component: UpdateSystemComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-interface',
            component: AddInterfaceComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-interface',
            component: UpdateInterfaceComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-user',
            component: AddUserComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-user',
            component: UpdateUserComponent,
            canActivateChild:[AuthGuard],
            data: {
                title: 'Update',
                expectedRole: '18'
            },

        },
        {
            path: 'add-group',
            component: AddGroupComponent,
            canActivateChild:[AuthGuard],
            data: {
                title: 'Add',
                expectedRole: '18'
            }
        },
        {
            path: 'update-group',
            component: UpdateGroupComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-role',
            component: AddRoleComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-role',
            component: UpdateRoleComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'master-transaction',
            component: TransactionComponent,
            data: {
                title: 'Transaction'
            }
        },
        {
            path :'transaction-payload',
            component:PayloadComponent,
            data:{
                title:'Payload'
            }
        },
        ]

        }
       ];

   @NgModule({
   imports: [RouterModule.forChild(routes)],
   exports: [RouterModule]
   })
   export class MasterSystemRoutingModule { }
   import { NgModule } from '@angular/core';
   import { Routes, RouterModule } from '@angular/router';

  // Layouts
   import { FullLayoutComponent } from './layouts/full-layout.component';
    import { SimpleLayoutComponent } from './layouts/simple- 
    layout.component';

    import{ AuthGuard } from './authguard/authguard';


    export const routes: Routes = [
   {
    path: '',
     redirectTo: 'pages/login',
     pathMatch: 'full',
     },
     {
    path: '',
    component: FullLayoutComponent,

    children: [
     {
    path: 'dashboard',
    loadChildren: './dashboard/dashboard.module#DashboardModule',
    canActivate:[AuthGuard],

  },
  {
    path: 'components',
    loadChildren: './components/components.module#ComponentsModule',
    canActivate:[AuthGuard],


    },
     {
    path: 'icons',
     loadChildren: './icons/icons.module#IconsModule'
     },
    {
    path: 'master-system',
    loadChildren: './master-system/master-   
    system.module#MasterSystemModule',
    canActivate:[AuthGuard],

     { 
       expectedRole: '1'
     }] ,
     { 
       expectedRole: '1',
       }

     },

    {
    path: 'mapping',
    loadChildren: './mapping/mapping.module#MappingModule',
    canActivate:[AuthGuard],

  },
   {
    path: 'widgets',
     loadChildren: './widgets/widgets.module#WidgetsModule'
      },
     {
    path: 'charts',
    loadChildren: './chartjs/chartjs.module#ChartJSModule',
    canActivate:[AuthGuard],
    canActivateChild:[AuthGuard],
      canActivateChild:[AuthGuard],
     data: [{ 
       expectedRole: '18'
     }]
    children:[
       {

      component: MasterInterfaceComponent
       }
        ],
    data: [{ 
      expectedRole: '18'
    }]
  },
  {
    path: 'search',
    loadChildren: './search/search.module#SearchModule',
    canActivate:[AuthGuard],
     canActivateChild: [ AuthGuard ],
     children: [
       {
          path: ':id',
           component: ArticleEditComponent
        }
       ] 

  },
  {
    path: 'eai',
    loadChildren: './eai/eai.module#EaiModule',
    canActivate:[AuthGuard],


  },
  {
    path: 'report',
    loadChildren: './report/report.module#ReportModule',
    canActivate:[AuthGuard],
      canActivateChild:[AuthGuard],
       data: [{ 
       expectedRole: '18'
        }]

       },

       ]
      },
     {
    path: 'pages',
   component: SimpleLayoutComponent,
    data: {
    title: 'Pages'
     },
     children: [
        {
        path: '',
       loadChildren: './pages/pages.module#PagesModule',
       }
      ]
      }
     ];

    @NgModule({
     imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}
主系统路由。ts

  import { Injectable } from '@angular/core';
   import { Router, CanActivate, ActivatedRouteSnapshot,          
 RouterStateSnapshot, CanActivateChild } from '@angular/router';


  @Injectable()


    export class AuthGuard implements CanActivateChild, CanActivate {
    expectedRole: any;
    accessId:boolean=false;
    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)           
       {
    if (localStorage.getItem('CurrentUser')) {

        console.log("IN AUTHGUARD", localStorage.getItem('CurrentUser'));
        console.log("inside CanActivate - true  ")
        return true;

      }
      else {

        this.router.navigate(['/pages/login'], { queryParams: { returnUrl:       

      state.url } });
        console.log("inside CanActivate - false -  

       this.router.navigate(['/pages/login'] ")
        return false;
          }
       }

     canActivateChild(route: ActivatedRouteSnapshot, state:            
     RouterStateSnapshot) {
     this.expectedRole = route.data;

        if ( localStorage.getItem('Access') == "18") {

              this.accessId = true;
              localStorage.setItem('accessId',            
      JSON.stringify(this.accessId));
              var output = localStorage.getItem('accessId');
              console.log("localStorage.getItem('accessId') = ",output)

             return true;
        }

        else 

        {
            this.router.navigate(['/pages/login'], { queryParams: {         
       returnUrl: state.url } });

            return false;            }

     }
     }
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import{ AuthGuard } from '.././authguard/authguard';
    import { MasterSystemsComponent } from './master-systems/master-   
   systems.component';
    import { AddSystemComponent } from './add-system/add-  
     system.component';
     import { UpdateSystemComponent } from './update-system/update- 
     system.component';



   const routes: Routes = [
    {
       path: '',
       data: {
        title: 'Master System'
       },
       children: [
        {
            path: 'master-systems',
            component: MasterSystemsComponent,
            data: {
                title: 'Master Systems'
            }
          },
          {
            path: 'master-interface',
            component: MasterInterfaceComponent,
            data: {
                title: 'Master Interface'
            }
        },
        {
            path: 'master-user',
            component: MasterUserComponent,
            data: {
                title: 'Master User'
            }
        },
        {
            path: 'master-group',
            component: GroupComponent,
            data: {
                title: 'Master Group'
            }
        },
        {
            path: 'master-role',
            component: RoleComponent,
            data: {
                title: 'Master Role'
            }
        },
        {
            path: 'add-system',
            component: AddSystemComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-system',
            component: UpdateSystemComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-interface',
            component: AddInterfaceComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-interface',
            component: UpdateInterfaceComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-user',
            component: AddUserComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-user',
            component: UpdateUserComponent,
            canActivateChild:[AuthGuard],
            data: {
                title: 'Update',
                expectedRole: '18'
            },

        },
        {
            path: 'add-group',
            component: AddGroupComponent,
            canActivateChild:[AuthGuard],
            data: {
                title: 'Add',
                expectedRole: '18'
            }
        },
        {
            path: 'update-group',
            component: UpdateGroupComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-role',
            component: AddRoleComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-role',
            component: UpdateRoleComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'master-transaction',
            component: TransactionComponent,
            data: {
                title: 'Transaction'
            }
        },
        {
            path :'transaction-payload',
            component:PayloadComponent,
            data:{
                title:'Payload'
            }
        },
        ]

        }
       ];

   @NgModule({
   imports: [RouterModule.forChild(routes)],
   exports: [RouterModule]
   })
   export class MasterSystemRoutingModule { }
   import { NgModule } from '@angular/core';
   import { Routes, RouterModule } from '@angular/router';

  // Layouts
   import { FullLayoutComponent } from './layouts/full-layout.component';
    import { SimpleLayoutComponent } from './layouts/simple- 
    layout.component';

    import{ AuthGuard } from './authguard/authguard';


    export const routes: Routes = [
   {
    path: '',
     redirectTo: 'pages/login',
     pathMatch: 'full',
     },
     {
    path: '',
    component: FullLayoutComponent,

    children: [
     {
    path: 'dashboard',
    loadChildren: './dashboard/dashboard.module#DashboardModule',
    canActivate:[AuthGuard],

  },
  {
    path: 'components',
    loadChildren: './components/components.module#ComponentsModule',
    canActivate:[AuthGuard],


    },
     {
    path: 'icons',
     loadChildren: './icons/icons.module#IconsModule'
     },
    {
    path: 'master-system',
    loadChildren: './master-system/master-   
    system.module#MasterSystemModule',
    canActivate:[AuthGuard],

     { 
       expectedRole: '1'
     }] ,
     { 
       expectedRole: '1',
       }

     },

    {
    path: 'mapping',
    loadChildren: './mapping/mapping.module#MappingModule',
    canActivate:[AuthGuard],

  },
   {
    path: 'widgets',
     loadChildren: './widgets/widgets.module#WidgetsModule'
      },
     {
    path: 'charts',
    loadChildren: './chartjs/chartjs.module#ChartJSModule',
    canActivate:[AuthGuard],
    canActivateChild:[AuthGuard],
      canActivateChild:[AuthGuard],
     data: [{ 
       expectedRole: '18'
     }]
    children:[
       {

      component: MasterInterfaceComponent
       }
        ],
    data: [{ 
      expectedRole: '18'
    }]
  },
  {
    path: 'search',
    loadChildren: './search/search.module#SearchModule',
    canActivate:[AuthGuard],
     canActivateChild: [ AuthGuard ],
     children: [
       {
          path: ':id',
           component: ArticleEditComponent
        }
       ] 

  },
  {
    path: 'eai',
    loadChildren: './eai/eai.module#EaiModule',
    canActivate:[AuthGuard],


  },
  {
    path: 'report',
    loadChildren: './report/report.module#ReportModule',
    canActivate:[AuthGuard],
      canActivateChild:[AuthGuard],
       data: [{ 
       expectedRole: '18'
        }]

       },

       ]
      },
     {
    path: 'pages',
   component: SimpleLayoutComponent,
    data: {
    title: 'Pages'
     },
     children: [
        {
        path: '',
       loadChildren: './pages/pages.module#PagesModule',
       }
      ]
      }
     ];

    @NgModule({
     imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}
app.routing.ts

  import { Injectable } from '@angular/core';
   import { Router, CanActivate, ActivatedRouteSnapshot,          
 RouterStateSnapshot, CanActivateChild } from '@angular/router';


  @Injectable()


    export class AuthGuard implements CanActivateChild, CanActivate {
    expectedRole: any;
    accessId:boolean=false;
    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)           
       {
    if (localStorage.getItem('CurrentUser')) {

        console.log("IN AUTHGUARD", localStorage.getItem('CurrentUser'));
        console.log("inside CanActivate - true  ")
        return true;

      }
      else {

        this.router.navigate(['/pages/login'], { queryParams: { returnUrl:       

      state.url } });
        console.log("inside CanActivate - false -  

       this.router.navigate(['/pages/login'] ")
        return false;
          }
       }

     canActivateChild(route: ActivatedRouteSnapshot, state:            
     RouterStateSnapshot) {
     this.expectedRole = route.data;

        if ( localStorage.getItem('Access') == "18") {

              this.accessId = true;
              localStorage.setItem('accessId',            
      JSON.stringify(this.accessId));
              var output = localStorage.getItem('accessId');
              console.log("localStorage.getItem('accessId') = ",output)

             return true;
        }

        else 

        {
            this.router.navigate(['/pages/login'], { queryParams: {         
       returnUrl: state.url } });

            return false;            }

     }
     }
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import{ AuthGuard } from '.././authguard/authguard';
    import { MasterSystemsComponent } from './master-systems/master-   
   systems.component';
    import { AddSystemComponent } from './add-system/add-  
     system.component';
     import { UpdateSystemComponent } from './update-system/update- 
     system.component';



   const routes: Routes = [
    {
       path: '',
       data: {
        title: 'Master System'
       },
       children: [
        {
            path: 'master-systems',
            component: MasterSystemsComponent,
            data: {
                title: 'Master Systems'
            }
          },
          {
            path: 'master-interface',
            component: MasterInterfaceComponent,
            data: {
                title: 'Master Interface'
            }
        },
        {
            path: 'master-user',
            component: MasterUserComponent,
            data: {
                title: 'Master User'
            }
        },
        {
            path: 'master-group',
            component: GroupComponent,
            data: {
                title: 'Master Group'
            }
        },
        {
            path: 'master-role',
            component: RoleComponent,
            data: {
                title: 'Master Role'
            }
        },
        {
            path: 'add-system',
            component: AddSystemComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-system',
            component: UpdateSystemComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-interface',
            component: AddInterfaceComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-interface',
            component: UpdateInterfaceComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-user',
            component: AddUserComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-user',
            component: UpdateUserComponent,
            canActivateChild:[AuthGuard],
            data: {
                title: 'Update',
                expectedRole: '18'
            },

        },
        {
            path: 'add-group',
            component: AddGroupComponent,
            canActivateChild:[AuthGuard],
            data: {
                title: 'Add',
                expectedRole: '18'
            }
        },
        {
            path: 'update-group',
            component: UpdateGroupComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'add-role',
            component: AddRoleComponent,
            data: {
                title: 'Add'
            }
        },
        {
            path: 'update-role',
            component: UpdateRoleComponent,
            data: {
                title: 'Update'
            }
        },
        {
            path: 'master-transaction',
            component: TransactionComponent,
            data: {
                title: 'Transaction'
            }
        },
        {
            path :'transaction-payload',
            component:PayloadComponent,
            data:{
                title:'Payload'
            }
        },
        ]

        }
       ];

   @NgModule({
   imports: [RouterModule.forChild(routes)],
   exports: [RouterModule]
   })
   export class MasterSystemRoutingModule { }
   import { NgModule } from '@angular/core';
   import { Routes, RouterModule } from '@angular/router';

  // Layouts
   import { FullLayoutComponent } from './layouts/full-layout.component';
    import { SimpleLayoutComponent } from './layouts/simple- 
    layout.component';

    import{ AuthGuard } from './authguard/authguard';


    export const routes: Routes = [
   {
    path: '',
     redirectTo: 'pages/login',
     pathMatch: 'full',
     },
     {
    path: '',
    component: FullLayoutComponent,

    children: [
     {
    path: 'dashboard',
    loadChildren: './dashboard/dashboard.module#DashboardModule',
    canActivate:[AuthGuard],

  },
  {
    path: 'components',
    loadChildren: './components/components.module#ComponentsModule',
    canActivate:[AuthGuard],


    },
     {
    path: 'icons',
     loadChildren: './icons/icons.module#IconsModule'
     },
    {
    path: 'master-system',
    loadChildren: './master-system/master-   
    system.module#MasterSystemModule',
    canActivate:[AuthGuard],

     { 
       expectedRole: '1'
     }] ,
     { 
       expectedRole: '1',
       }

     },

    {
    path: 'mapping',
    loadChildren: './mapping/mapping.module#MappingModule',
    canActivate:[AuthGuard],

  },
   {
    path: 'widgets',
     loadChildren: './widgets/widgets.module#WidgetsModule'
      },
     {
    path: 'charts',
    loadChildren: './chartjs/chartjs.module#ChartJSModule',
    canActivate:[AuthGuard],
    canActivateChild:[AuthGuard],
      canActivateChild:[AuthGuard],
     data: [{ 
       expectedRole: '18'
     }]
    children:[
       {

      component: MasterInterfaceComponent
       }
        ],
    data: [{ 
      expectedRole: '18'
    }]
  },
  {
    path: 'search',
    loadChildren: './search/search.module#SearchModule',
    canActivate:[AuthGuard],
     canActivateChild: [ AuthGuard ],
     children: [
       {
          path: ':id',
           component: ArticleEditComponent
        }
       ] 

  },
  {
    path: 'eai',
    loadChildren: './eai/eai.module#EaiModule',
    canActivate:[AuthGuard],


  },
  {
    path: 'report',
    loadChildren: './report/report.module#ReportModule',
    canActivate:[AuthGuard],
      canActivateChild:[AuthGuard],
       data: [{ 
       expectedRole: '18'
        }]

       },

       ]
      },
     {
    path: 'pages',
   component: SimpleLayoutComponent,
    data: {
    title: 'Pages'
     },
     children: [
        {
        path: '',
       loadChildren: './pages/pages.module#PagesModule',
       }
      ]
      }
     ];

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

我认为,你的问题是关于URL的许可。每个url指向一个组件。我有一个简单的解决办法。在localStorage中保存身份验证时,还要保存用户角色。然后在Ngonit方法检查中,例如,如果用户不是管理员,则不要访问该组件

if(localStorage.getItem('role') != 'admin'){
    this.router.navigate(['/']);
}

当调用url时,实际上是调用一个组件,在一个组件中,它首先运行,然后如果用户没有权限,则转到主页。

您是否尝试在
路径:主系统中使用canActiveChild

const routes:routes=[
...
{
路径:'主系统',
loadChildren:'/主系统/主系统.模块#主系统模块',
canActivateChild:[AuthGuard]
}
...

];在我看来,您的做法是错误的,您可以在api级别对path进行身份验证,让您处理从启动的请求接收到的响应。不,这不起作用。你能检查一下吗?你能在stackblitz中创建一个在线示例吗?它可以节省你更多的时间,并得到一个答案