首页 > 解决方案 > 如何在 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

标签: angulartypescriptasynchronousasync-awaitzone.js

解决方案


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

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

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

async run() { // TODO }

推荐阅读