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

Angular 17中如何在Interceptor中正确使用加载功能?

Angular 17 拦截器「ERROR TypeError: next is not a function」修复方案

你写的函数式拦截器逻辑没问题,但核心错误是调用next的方式不对——Angular 17+ 的HttpInterceptorFn里,next是一个包含handle方法的对象,不是直接可调用的函数,旧类式拦截器的调用逻辑不适用于新的函数式写法。

正确的实现代码:

export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
  const loadingService = inject(LoadingService);
  loadingService.show();
  
  return next.handle(req).pipe(
    finalize(() => {
      loadingService.hide();
    })
  );
};

关键改动说明:

  • 把原本的next(req)替换为next.handle(req),这是Angular 17+函数式拦截器的标准调用方式
  • 其余的加载状态控制逻辑(inject服务、finalize钩子)是正确的,可以保留

额外提示(注册拦截器):

在Angular 17的独立应用中,需要在app.config.ts里通过provideHttpClient注册拦截器,示例:

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([loadingInterceptor])),
    // 其他服务配置
  ]
};

内容的提问来源于stack exchange,提问作者Rafael Moura

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:42:04