[英]Angular navigate causing infinte loop in route guarding
我有這些路線:
{path: '', redirectTo: 'login', pathMatch: 'full'},
{path: 'todos', component: TodosComponent, canActivate: [AuthGuard]},
{path: 'add-todo', component: AddTodoComponent, canActivate: [AuthGuard]},
{path: 'todo/:id', component: TodoComponent, resolve: {
todo: TodoResolver
}, canActivate: [AuthGuard]
},
{path: 'login', component: LoginComponent, canActivate: [IsLoggedIn]},
{path: '**', redirectTo: ''}
]
有了這個守衛:
export class IsLoggedInGuard implements CanActivate {
constructor(private storageService: StorageService, private router: Router, private authService: AuthService) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const user = this.storageService.getFromStorage('user');
if(user) {
this.authService.setUser(user, false);
this.router.navigate(['todos']);
return false;
}
return true;
}
}
在本地工作正常,但是當我部署它時,它進入了無限循環。
為什么會出現無限循環,我該如何解決?
很可能您正在進入無限循環,因為 / 路徑被重定向到受 AuthGuard 本身保護的路徑。
例如。 您嘗試訪問受守衛保護的路由 A,它重定向到路由 B(基本路由 / ),路由 B 可能重定向(查看路由中的 redirectTo 屬性)到路由 C,它也受 AuthGuard 保護,導致以下路線。
A -> B -> C -> B -> C...
你的守衛應該是
export class IsLoggedInGuard implements CanActivate {
constructor(private storageService: StorageService, private router:
Router, private authService: AuthService) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean
| UrlTree {
const user = this.storageService.getFromStorage('user');
if(user) {
this.authService.setUser(user, false);
this.router.navigate(['todos']);
}
return true;
}
}
確保路由定義正確。
謝謝!
要解決此問題,您應該確保 IsLoggedInGuard 守衛僅應用於登錄路由,而不應用於任何其他路由。 您可以通過像這樣修改路由配置來做到這一點:
{
path: 'login',
component: LoginComponent,
canActivate: [IsLoggedInGuard]
},
{
path: 'todos',
component: TodosComponent,
canActivate: [AuthGuard]
},
{
path: 'add-todo',
component: AddTodoComponent,
canActivate: [AuthGuard]
},
{
path: 'todo/:id',
component: TodoComponent,
resolve: {
todo: TodoResolver
},
canActivate: [AuthGuard]
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.