首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当我尝试使用angular guard根据用户角色进行路由时,浏览器冻结

当我尝试使用angular guard根据用户角色进行路由时,浏览器冻结
EN

Stack Overflow用户
提问于 2018-09-04 20:21:56
回答 1查看 347关注 0票数 0

我刚开始使用angular6,目前在使用angular提供的基于用户角色的不同页面时遇到了问题。我在应用程序中有3个主要角色

这是我的AuthGard auth.guard.ts

代码语言:javascript
运行
复制
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService,
    private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | 
boolean {
console.log(this.auth.isLoggedIn())
if (this.auth.isLoggedIn()) {
  return true;
}  

this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } })
return false;
}
}

这是我的角色守卫role.guard.ts

代码语言:javascript
运行
复制
export class RoleGuard implements CanActivate {
  constructor(private _auth: AuthService, private _router: Router) { }

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
switch (this._auth.getRole()) {
  case "STUDENT":
    this._router.navigate(['/']);
    return true;
  case "DEPARTMENT":
    this._router.navigate(['/department']);
    return true;
  case "FACULTY":
    this._router.navigate(['/faculty']);
    return true;
  default:
    return false;
   }
  }
}

和我的模块student.module.ts

代码语言:javascript
运行
复制
{ path: '', component: DashboardComponent, canActivate: [AuthGuard, RoleGuard] },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard, RoleGuard] }

我遗漏了什么?

EN

回答 1

Stack Overflow用户

发布于 2019-07-20 02:01:01

在使用angular 6和更高版本时,请确保不要将它们包含在提供程序根中,因为服务已经是根:‘providedIn’。例如:

代码语言:javascript
运行
复制
@Injectable({
  providedIn: 'root'
})

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52166256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档