Я должен установить аутентификацию для пользователя, когда только определенный пользователь может получить доступ к кнопке, для этого я использовал localStorage, так что я скрываю кнопку, когда любой пользователь, кроме администратора, пытается получить к ней доступ.
Но есть и другой способ, которым пользователь может получить доступ к кнопкам, используя такие ссылки, как:
http://localhost:4200/#/master-system/add-user
или
http://localhost:4200/#/master-system/update-user.
Так, чтобы отключить ребенка (я думаю,это ребенок, пожалуйста, поправьте меня, если я ошибаюсь), я добавил canActivateChild в файл authguard.ts и некоторые изменения в файле app.routing.ts, но он не работает.
Кроме того, у меня естьмного файлов routing.ts.Это как, у меня есть 5 компонентов внутри master-системы, и у этой master-системы есть свой собственный файл 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; }
}
}
master-system-routing.ts
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 { }
app.routing.ts
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 {}