Angular应用初始化时如何获取跳转初始URL中的token参数值
Angular应用初始化阶段捕获原始URL获取token方案
实现步骤
- 核心逻辑:在Angular路由接管跳转、修改地址栏之前,直接读取原生
window对象的地址属性,不要依赖Angular路由提供的参数获取能力,避免跳转后参数丢失。 - 第一步:在应用最早的初始化节点读取原始URL,推荐使用
APP_INITIALIZER钩子,确保逻辑在路由启动前执行。 - 第二步:解析原始URL提取token,适配你提供的URL格式示例,代码如下:
// 1. 先定义存储token的公共服务,如 auth.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class AuthService { public token: string | null = null; }
// 2. 在 app.module.ts 中配置初始化钩子 import { NgModule, APP_INITIALIZER } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AuthService } from './auth.service'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; // 初始化token的工厂函数 export function initToken(authService: AuthService) { return () => { // 直接读取原生地址,此时Angular还未修改地址栏 const originalUrl = window.location.href; const url = new URL(originalUrl); // 适配两种参数格式,按需选用即可 let token: string | null = null; // 格式1:路径携带参数 如 http://localhost:4200/token=xxx const tokenPath = url.pathname.split('/').find(part => part.startsWith('token=')); if (tokenPath) token = tokenPath.split('=')[1]; // 格式2:查询参数 如 http://localhost:4200/?token=xxx if (!token) token = url.searchParams.get('token'); authService.token = token; return Promise.resolve(); }; } @NgModule({ declarations: [AppComponent], imports: [BrowserModule, AppRoutingModule], providers: [ // 注册初始化钩子,优先执行token读取逻辑 { provide: APP_INITIALIZER, useFactory: initToken, deps: [AuthService], multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
- 第三步:业务代码中直接注入
AuthService即可读取到提前捕获的token值。
注意事项
不要使用
ActivatedRoute等Angular路由相关的API获取初始参数,你看到的地址跳转是Angular路由完成初始化后替换了地址栏,此时路由API只能拿到跳转后的#/路由的参数,已经丢失了原始URL的内容。
内容的提问来源于stack exchange,提问作者Blaque_Mani
相关产品推荐
相关产品推荐

