我已经根据用户角色设置了路由并显示页面。为此,我在路线上使用警卫。我正在从 Appcomponent 类的服务中提取 userRole,并在主服务文件中使用 set 和 get 方法。现在的问题是,在我获得角色之前,会发生路由并导航到错误的 url,因为那时它还没有角色。从下一个电话开始很艰难,它可以正常工作。让我分享代码:- 1.这是警卫类:-
export class HomeGuard implements CanActivate {
constructor(private _router: Router,private mainService: MainService) {
}
canActivate(): boolean {
let userRoles:any;
alert('HomeGuard');
userRoles = this.mainService.getSavedUserRole();
//userRoles = ['Profile Manager','Operations','Shipper'];
alert('userRoles are here'+userRoles);
console.log('here in homeguard');
if(userRoles) {
if(userRoles.some(x => x === 'Shipper') || userRoles.some(x => x === 'Admin'))
return true;
}
this._router.navigate(['/notfound']);
return false;
}
}
这是我从服务中提取 userRole 的 AppComponent:-
export class AppComponent { savedUserRoles:any; constructor(private translate: TranslateService,private mainService: MainService) { console.log('Environment config', Config); // this language will be used as a fallback when a translation isn't found in the current language translate.setDefaultLang(AppSettings.LNG_TYPE); // the lang to use, if the lang isn't available, it will use the current loader to get them translate.use(AppSettings.LNG_TYPE); this.mainService.getCurrentUser().subscribe(result => { this.savedUserRoles = JSON.parse(JSON.parse(result._body).Data).Roles; console.log('sdfghj'+this.savedUserRoles); this.mainService.setSavedUserRole(this.savedUserRoles); }); } }
这是我定义了 set 和 get 方法的主要服务:-
setSavedUserRole(name: any) { console.log('main'+name); this._userRoles = 名称;}
getSavedUserRole() { return this._userRoles; }