Angular 14+Ionic 6已登录用户重启应用自动跳转首页问题
问题修复:Angular 14 + Ionic 6 重启应用后已登录用户自动跳转首页
你的代码核心问题出在守卫职责混淆和路径判断错误,导致已登录状态下重启应用仍会进入登录页,以下是具体修复方案:
1. 实现缺失的 AutoLoginGuard
你的路由配置中,login 路由使用了 AutoLoginGuard 但并未实现它,反而把自动登录的逻辑错误放在了保护 home 路由的 AuthGuard 里。AutoLoginGuard 的职责是拦截登录页访问,判断用户已登录时直接跳转首页:
import { Injectable } from '@angular/core'; import { CanLoad, Route, Router, UrlSegment } from '@angular/router'; import { Observable } from 'rxjs'; import { filter, map, take } from 'rxjs/operators'; import { AuthenticationService } from './authentication.service'; @Injectable({ providedIn: 'root' }) export class AutoLoginGuard implements CanLoad { constructor( private authService: AuthenticationService, private router: Router ) {} canLoad( route: Route, segments: UrlSegment[] ): Observable<boolean | UrlTree> { return this.authService.isAuthenticated.pipe( filter(val => val !== null), // 等待认证状态初始化完成 take(1), map(isAuthenticated => { if (isAuthenticated) { this.router.navigateByUrl('/home'); return false; // 阻止加载登录页模块 } return true; // 未登录,允许进入登录页 }) ); } }
2. 修正 AuthGuard 的逻辑错误
原 AuthGuard 中错误地判断 route.path === '/login',但 route.path 获取的是不带斜杠的路径名(即 'login'),而且 AuthGuard 的职责应该是保护首页路由,仅在未登录时跳转到登录页:
import { Injectable } from '@angular/core'; import { CanLoad, Route, Router, UrlSegment } from '@angular/router'; import { Observable } from 'rxjs'; import { filter, map, take } from 'rxjs/operators'; import { AuthenticationService } from './authentication.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanLoad { constructor( private authService: AuthenticationService, private router: Router ) {} canLoad( route: Route, segments: UrlSegment[] ): Observable<boolean | UrlTree> { return this.authService.isAuthenticated.pipe( filter(val => val !== null), take(1), map(isAuthenticated => { if (!isAuthenticated) { this.router.navigateByUrl('/login'); return false; } return true; // 已登录,允许加载首页模块 }) ); } }
3. 保持路由配置不变
你的路由配置本身没问题,现在配合正确实现的两个守卫,就能实现预期逻辑:
const routes: Routes = [ { path: 'login', loadChildren: () => import('./login/login.module').then(m => m.LoginPageModule), canLoad: [AutoLoginGuard] }, { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomePageModule), canLoad: [AuthGuard] }, ];
关键说明
AuthenticationService中loadToken是异步操作,所以用BehaviorSubject<boolean>(null)作为初始状态,通过filter(val => val !== null)确保等待认证状态加载完成后再处理路由跳转- 应用启动时会触发默认路由重定向到
login,此时AutoLoginGuard会检查登录状态:已登录则跳转到home,未登录则允许进入登录页 AuthGuard会拦截所有直接访问home的请求,未登录时强制跳转到登录页
内容的提问来源于stack exchange,提问作者weinde
相关产品推荐
相关产品推荐

