加载未登录的组件时卡住



当用户未登录时重定向时,我有一个问题。在我的项目中,我有两个管理员和用户的警卫,然后我使用@angular/fire/auth-guard库的函数来重定向是否登录,如果没有。问题是,如果我添加我自己创建的保护,检查您是否登录的每个组件的保护停止工作,这使页面加载并且永远不会结束,而我的工作。下面是我的代码示例:

在这段代码中,我有两个RolUserGuard和RoleAdminGuard工作,但AuthGuard的home和admin不工作,他们被捕获加载没有返回到登录页面。相反,如果你已经登录并尝试重定向到登录页面,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}
]

我做错了什么吗?可能是因为数据属性的原因,而在添加第二个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;
}

对于这种情况,我的解决方案是删除authguard并在每个guard中使用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;
}

你应该为RoleUserGuard做同样的事情,但条件(角色)不同。

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

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

只使用一个守卫(RoleGuard)
RoleGuard:

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;
}

我希望这对你有帮助。

最新更新