當用戶未登錄時重定向時出現問題。在我的專案中,我有兩個 Guards 用于管理員和用戶,然后我使用 @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;
}
uj5u.com熱心網友回復:
我對這種情況的解決方案是,洗掉 authGurad 并在每個警衛中使用 UserService 來檢查用戶是否已登錄:
角色管理員衛士:
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 中使用這樣的用戶字典。
用戶服務:
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;
}
我希望這對你有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477926.html
下一篇:是否匯出樣式組件
