Angular V18:NullInjectorError:没有 _NgZone 的提供者

问题描述 投票:0回答:1

我目前正在从 Angular 版本 17 升级到版本 18.0.0。我的一个组件依赖于从

NgZone
 导入 
@angular/core.

例如-

  this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        this.expand()
      }, 0);
    });

angular.json
具有类似
"polyfills": ["zone.js"]
的配置。

但是当运行应用程序时,浏览器开发工具控制台上会出现错误。

NullInjectorError: No provider for _NgZone!

如果需要任何其他信息,请随时通知我。您能帮忙吗?

谢谢!

javascript angular
1个回答
0
投票

确保您已将

provideZoneChangeDetection
添加到
ApplicationConfig
的提供者数组中。

应用程序.config.ts

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes)]
};

组件代码:

import { Component, NgZone, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent {
  title = 'test';

  constructor(private ngZone: NgZone) {}

  ngOnInit() {
    this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        alert('zone hi!');
      }, 0);
    });
  }
}

Stackblitz 演示 ->
cd test
->
npm I && npm run start

© www.soinside.com 2019 - 2024. All rights reserved.