【问题标题】:How to run async function outside ngZone? [duplicate]如何在 ngZone 之外运行异步功能? [复制]
【发布时间】:2025-12-25 18:05:11
【问题描述】:

我试图在当前区域之外调整脚本:

  async ngAfterViewInit(): Promise<void> {
     this.ngZone.runOutsideAngular(() => {
       await this.run();
     });
  }
  
  async run() { // TODO }

我收到此错误:

'await' expressions are only allowed within async functions and at the top levels of modules.ts

【问题讨论】:

标签: angular typescript asynchronous async-await zone.js


【解决方案1】:

ngAfterViewInit 函数是异步的,但是您使用 this.ngZone.runOutsideAngular 和非异步回调函数。

你的代码需要看起来像这样......

ngAfterViewInit(): void {
    this.ngZone.runOutsideAngular(async () => {
        await this.run();
    });
}

async run() { // TODO }

【讨论】: