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

本地运行Angular应用突发NullInjectorError: No provider for ActivatedRoute错误

解决Angular中ActivatedRoute无提供者的NullInjectorError问题

问题背景

本地运行Angular应用时未修改任何代码,突然出现错误,但相同代码库在配置一致的另一台机器上可正常运行。
Node版本:v16.17.0

报错信息

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[ActivatedRoute -> ActivatedRoute -> ActivatedRoute]: NullInjectorError: No provider for ActivatedRoute!

报错截图

报错截图

解决步骤

  1. 清理本地依赖与缓存
    本地依赖缓存损坏是这类跨机器不一致问题的常见原因:

    • 删除node_modules文件夹:
      # macOS/Linux
      rm -rf node_modules
      # Windows
      rmdir /s /q node_modules
      
    • 删除package-lock.json(npm环境)或yarn.lock(yarn环境)
    • 重新安装依赖:npm install 或 yarn install
    • 清理Angular CLI缓存:ng cache clean
  2. 确认模块配置正确性
    虽代码未修改,但本地缓存可能导致加载异常,需检查:

    • 使用ActivatedRoute的模块已导入RouterModule,根模块需配置RouterModule.forRoot(routes),特性模块需配置RouterModule.forChild(routes)
    • 禁止手动在providers数组中添加ActivatedRoute,该服务由RouterModule自动提供
  3. 重启开发环境

    • 终止当前Angular开发服务器(Ctrl+C),重新启动:ng serve
    • 重启IDE(如VS Code),清除编辑器缓存
  4. 同步Node与Angular CLI版本
    再次确认本地与另一台机器的版本一致性:

    • 查看本地版本:ng version
    • 若CLI版本不一致,卸载本地CLI并安装对应版本:
      npm uninstall -g @angular/cli
      npm install -g @angular/cli@x.x.x # 替换为目标机器的CLI版本号
      

内容的提问来源于stack exchange,提问作者Pubudu Mahesh Meththananda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:57:12