我想在我的 Angular 6 项目之一中使用 RoleGuard 服务。我role-guard.service.ts
在“ _guards
”文件夹下创建了一个文件 - ''。现在在路由文件中,我声明了与下面相同的内容并尝试实现相同的内容。请注意,我有一个共享模块,我没有在导出中声明 roleguardservice。
import { RoleGuardService } from '../../_guards/role-guard.service';
const routes: Routes = [
{ path: 'edit-account-info', component: EditAccountInfoComponent, canActivate: [RoleGuardService] },
....
....
]
}
下面是我的app.module.ts file
:
import { AuthGuard, DisableAuthGuard} from '../../_guards/auth.guard';
....
....
exports : [
//
],
providers: [AuthGuard, DisableAuthGuard, {
provide: RECAPTCHA_SETTINGS,
useValue: {
siteKey: environment.recaptchasiteKey,
} as RecaptchaSettings,
}]
我想更改路线取决于用户角色。就像,如果用户角色类型 1,那么他将重定向到“edit-account-info”,否则(如果用户角色类型 2)他将重定向到“代理/编辑帐户信息”。如果用户角色类型 2 想要访问路径“edit-account-info”,他将转到“unauthorize”页面。
但是要实现它,当我想访问页面“edit-account-info”时,它会向我显示错误:
未捕获(承诺):错误:StaticInjectorError(AppModule)[RoleGuardService]: StaticInjectorError(Platform: core)[RoleGuardService]: NullInjectorError: No provider for RoleGuardService!错误:StaticInjectorError(AppModule)[RoleGuardService]: StaticInjectorError(Platform: core)[RoleGuardService]: NullInjectorError: No provider for RoleGuardService!…………
以下是role-guard.sevice.ts
文件内容:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router';
//import { AuthGuard } from './auth.guard';
import { CommonService } from './../services/common.service';
import { AuthGuard, DisableAuthGuard} from './auth.guard';
@Injectable()
export class RoleGuardService implements CanActivate {
private userDetails: any;
public user_salt: any;
public roleName: any;
constructor(
//public auth: AuthService,
public router: Router,
private commService: CommonService,
private location: Location,
) {
}
canActivate(route: ActivatedRouteSnapshot): boolean {
this.userDetails = this.commService.getSession('user');
this.user_salt = this.commService.getSession('user_salt');
const resultStorage = JSON.parse(this.commService.localstorageDecryption(this.userDetails, this.user_salt, 'N'));
if (this.roleName === resultStorage.type) {
return true;
}
// navigate to not found page
this.router.navigate(['/404']);
return false;
}
}