gpt4 book ai didi

angular - 在加载未登录的组件时卡住

转载 作者:行者123 更新时间:2023-12-05 05:41:15 26 4
gpt4 key购买 nike

我在用户未登录时重定向时遇到问题。在我的项目中,我有两个 Guards 用于 Admin 和 User,然后我使用 @angular/fire/auth-guard 库的功能在登录时进行重定向在,如果不是。问题是如果我添加我自己创建的守卫,检查你是否登录的每个组件的守卫停止工作,这会保持页面加载并且永远不会结束,而不是我的工作。这是我的代码示例:

在这段代码中,我同时让 RolUserGuard 和 RoleAdminGuard 工作,但是 home 和 admin 的 AuthGuard 不工作,他们在加载时被抓到而没有返回登录页面。相反,如果您已登录并尝试重定向到登录页面,AuthGuard 会起作用。

const redirectUnauthorizedToLogin = () => redirectUnauthorizedTo(['']);
const redirectLoggedInToHome = () => redirectLoggedInTo(['home']);

const routes : Routes = [
{path : '',redirectTo: 'login', pathMatch: 'full'},
{path : 'login', component : LoginComponent, canActivate: [AuthGuard], data: {authGuardPipe: redirectLoggedInToHome}},
{path : 'home', component : HomeComponent, canActivate: [AuthGuard,RoleUserGuard], data: {authGuardPipe: redirectUnauthorizedToLogin} },
{path : 'admin', component : AdminComponent, canActivate: [AuthGuard,RoleAdminGuard], data: {authGuardPipe: redirectUnauthorizedToLogin}, children:[
{path : '', component : AdminUsersComponent},
{path : 'user/:id', component: DetailsComponent}
]},
{path : '**', component: PageNotFoundComponent}
]

我做错了什么吗?可能是因为 data 属性,并且在添加第二个 Guard 时它没有正确检测到它?什么都有帮助

我把其他守卫的代码留给你,尽管它实际上是一样的,只是它改变了而不是用户的 amin,反之亦然。

  canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

const rol = localStorage.getItem('rolUser');

if(rol!=='admin'){
this.router.navigate(['/home']);
return false;
}

return true;
}

最佳答案

我针对这种情况的解决方案是,删除 authGurad 并在每个守卫中使用 UserService 来检查用户是否已登录:

RoleAdminGuard:

  canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const isLoggedIn = this.userService.isLoggedIn();
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
const rol = localStorage.getItem('rolUser');

if (rol !== 'admin'){
this.router.navigate(['/home']);
return false;
}

return true;
}

并且您应该为具有不同条件( Angular 色)的 RoleUserGuard 做同样的事情。

或者

我们可以在 UserService 中使用这样的用户字典。
用户服务:

userAccess= {
home: 'user',
admin: 'admin'
}

并且只用一个守卫(RoleGuard)
Angular 色守卫:

  canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const isLoggedIn = this.userService.isLoggedIn();
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
const rol = localStorage.getItem('rolUser');
const userAccess = this.userService.userAccess[next.url]
if (rol !== userAccess) {
const navigateTo = rol === 'admin' ? '/admin' : '/home';
this.router.navigate([navigateTo]);
return false;
}

return true;
}

希望对你有帮助

关于angular - 在加载未登录的组件时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72303634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com