我需要创建一种方法来检查数据访问是否等于next.data.access。 我可以使用include方法,因为它是一个数组。 数组中的数据访问值之一只能返回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}
]},
答案 0 :(得分:0)
为此,您不能使用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);