我已根据用户角色设置路由并显示页面。为此我在路线上使用守卫。我从Appcomponent类中的服务中提取userRole,并在main-service文件中使用set和get方法。现在的问题是,在我获得角色之前,路由发生并导航到错误的URL,因为它当时没有角色。下次通话很难,它可以正常工作。让我分享一下代码: - 这是警卫班: -
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;
}
}
这是AppComponent,我从服务中提取userRole: -
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( '主' +名); this._userRoles = name; }
getSavedUserRole() {
return this._userRoles;
}