Angular 16获取地址栏初始URL并实现登录后重定向
问题描述
使用Angular 16,后端邮件包含跳转至对应页面的URL。未认证用户访问该URL时,会先跳转至登录页,但登录完成后默认跳转到仪表盘。需求是登录后重定向至邮件提供的目标URL,但首次获取router.url仅返回/。
解决方案
1. 修改登录守卫,捕获目标URL
更新SignedInGuard,在用户未登录时,将当前尝试访问的原始URL存储到AuthService,再重定向到登录页:
export class SignedInGuard implements CanActivate { readonly #authService = inject(AuthService); readonly #router = inject(Router); canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> { return defer(() => { if (!this.#authService.isLoggedIn() && !this.#authService.isLoadingSilentAuth()) { // 存储用户原本要访问的URL this.#authService.setRedirectUrl(state.url); return this.#authService.dispatchSilentAuth$().pipe( switchMap(() => { if (!this.#authService.isLoggedIn() && !this.#authService.isLoadingSilentAuth()) { // 重定向到登录页 return of(this.#router.createUrlTree(['/auth'])); } return of(true); }) ); } return of(true); }); } }
2. 在AuthService中添加URL存储逻辑
新增变量和方法来保存、获取目标URL:
// AuthService内部代码 private redirectUrl: string = '/dashboard'; // 默认跳转仪表盘 setRedirectUrl(url: string): void { // 排除登录页和根路径,避免无效跳转 if (!url.includes('/auth') && url !== '/') { this.redirectUrl = url; } } getRedirectUrl(): string { const targetUrl = this.redirectUrl; // 用完重置默认值,避免后续登录重复跳转 this.redirectUrl = '/dashboard'; return targetUrl; }
3. 修改登录成功后的重定向逻辑
将所有登录方式(如SSO、JWT、凭证登录)中的this.redirectDashboard();替换为获取存储的URL并跳转:
// 以SSO登录的dispatch方法为例 subscribe({ next: (user) => { this.sucessLogging(user); // 替换原redirectDashboard逻辑 const targetUrl = this.getRedirectUrl(); this.#router.navigateByUrl(targetUrl); // Info message this.displayStandardMessage(MessageType.SignedIn); }, })
4. 验证路由配置兼容性
当前路由中''重定向到/dashboard的规则不会影响逻辑,因为setRedirectUrl已经排除了根路径/,只有用户访问邮件中的具体URL时才会存储目标地址。
内容的提问来源于stack exchange,提问作者Blank
相关产品推荐
相关产品推荐

