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
相关产品推荐
相关产品推荐

