You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular拦截器中如何获取服务数据,调用AuthService方法报undefined怎么解决?

问题诊断

核心报错原因

  • app.module.ts中拦截器的依赖注入配置错误:你在useFactory的参数里声明了需要Router和AuthService两个依赖,但deps数组只写了[Router],缺少AuthService的声明,导致Angular注入时没有给第二个参数传值,authService最终是undefined,调用它的方法自然抛出空指针错误。
  • 额外隐藏bug:你在intercept方法里已经克隆了带身份头的authReq,但最终传给next.handle()的还是原始的request,即使解决了注入问题,请求头也不会生效。

修复步骤

  1. 修正app.module.ts中的拦截器配置,在deps数组中添加AuthService
providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useFactory: (router: Router, authService: AuthService) => {
            return new AuthInterceptor(router, authService);
        },
        multi: true,
        deps: [Router, AuthService] // 新增AuthService依赖声明
    }
],
  1. 修正auth.interceptor.ts中的返回逻辑,把克隆后的请求传给处理链
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('intercept', request);
    const authReq = request.clone({
        headers: request.headers.set(
            this.authService.getAuthenticationKey(), 
            this.authService.getAuthenticationToken()
        )
    });
    return next.handle(authReq); // 替换为克隆后的带认证头的请求
}

可选优化

如果存在未登录的场景,可以先判断令牌是否存在,避免给公共接口也添加无效的认证头:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.authService.getAuthenticationToken();
    if (token) {
        const authReq = request.clone({
            headers: request.headers.set(
                this.authService.getAuthenticationKey(), 
                token
            )
        });
        return next.handle(authReq);
    }
    return next.handle(request);
}

内容的提问来源于stack exchange,提问作者Vala Khosravi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:15:05