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

Angular 17升级至18遇NullInjectorError: _NgZone无提供者问题求助

解决Angular 18升级后NgZone的NullInjectorError问题

以下是针对你遇到的NullInjectorError: No provider for _NgZone!错误的具体解决方案:

  • 检查组件是否为独立组件
    如果你的组件设置了standalone: true,Angular 18默认不会自动注入NgZone依赖。你需要在组件元数据的providers数组中显式声明NgZone:

    import { Component, NgZone } from '@angular/core';
    
    @Component({
      selector: 'app-your-component',
      templateUrl: './your-component.component.html',
      standalone: true,
      providers: [NgZone]
    })
    export class YourComponent {
      constructor(private ngZone: NgZone) {}
    
      // 你的业务代码...
    }
    

    或者更推荐用inject()函数直接获取(独立组件的最佳实践):

    import { Component, inject, NgZone } from '@angular/core';
    
    @Component({
      selector: 'app-your-component',
      templateUrl: './your-component.component.html',
      standalone: true
    })
    export class YourComponent {
      private ngZone = inject(NgZone);
    
      // 你的业务代码...
    }
    
  • 禁止直接依赖内部类_NgZone
    确认你的代码中从未导入或使用_NgZone——这是Angular的内部实现类,外部代码不应该直接依赖,所有NgZone相关逻辑都要基于@angular/core导出的NgZone类。

  • 确保zone.js正确加载
    虽然你在angular.json中配置了polyfills,但Angular 18可能要求在main.ts顶部显式导入zone.js:

    import 'zone.js';
    

    同时更新到最新版本的zone.js:

    npm install zone.js@latest
    
  • NgModule场景下检查提供者配置
    如果你的组件属于某个NgModule,确认该Module的providers数组中包含NgZone,或者没有误删相关的提供者配置。

内容的提问来源于stack exchange,提问作者cj devin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:42:07