如何在Angular17的HttpInterceptorFn中使用非废弃NGRX选择器
Angular 17 HttpInterceptorFn 结合 NGRX Store 获取 Token 实现方案
直接上可运行的实现代码,完全匹配你的需求:
import { HttpInterceptorFn } from '@angular/common/http'; import { inject } from '@angular/core'; import { Store } from '@ngrx/store'; import { switchMap, take } from 'rxjs/operators'; import { selectUser } from './path-to-your-user-selectors'; // 替换为你的选择器实际路径 export const authInterceptor: HttpInterceptorFn = (req, next) => { // 跳过登录接口,根据你的实际接口路径调整判断逻辑 if (req.url.includes('/api/auth/login')) { return next(req); } const store = inject(Store); return store.select(selectUser).pipe( take(1), // 仅获取当前Store的最新Token值,无需持续订阅 switchMap(user => { // 克隆请求并添加Token头(仅当Token存在时) const authReq = user?.token ? req.clone({ setHeaders: { Authorization: `Bearer ${user.token}` } }) : req; return next(authReq); }) ); };
关键细节说明
- 依赖注入:在函数式拦截器中使用
inject(Store)获取NGRX Store实例,符合Angular 17的DI规范。 - Store数据获取:通过
store.select(selectUser)调用你的NGRX选择器,替代原localStorage读取逻辑。 - 避免废弃API:使用
switchMap替代已废弃的map,将Store的数据流切换到HTTP请求流,符合RxJS最新规范。 - 请求不可变性:HTTP请求对象是不可变的,必须通过
req.clone()修改请求头后再传递给next()。 - 订阅控制:
take(1)确保只获取一次当前Store中的Token值,避免不必要的持续订阅(若需实时监听Token变化,可移除该操作符)。
拦截器注册(保持原有方式)
在app.config.ts中注册拦截器:
import { provideHttpClient, withInterceptors } from '@angular/common/http'; import { authInterceptor } from './path-to-your-interceptor'; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(withInterceptors([authInterceptor])), // 其他应用提供者... ] };
内容的提问来源于stack exchange,提问作者Archimede
相关产品推荐
相关产品推荐

