网站搜索

angular - 如何在 ngZone 外运行异步函数?


我已经尝试在当前区域外运行脚本:

  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

答案#1

ngAfterViewInit 函数是异步的,但你却使用了 this.ngZone.runOutsideAngular,并传入了一个非异步的回调函数。

你的代码需要像这样…

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

async run() { // TODO }