【问题标题】:Need help on how to do callback in Angular需要有关如何在 Angular 中进行回调的帮助
【发布时间】:2023-01-11 17:16:45
【问题描述】:
  async getExample(value: string) {
    // this must be done first
    if (this.componentRef) {
      this.componentRef.location.nativeElement.classList.add('fadeMeOut');    
    }
    // this must be done second
    switch (value) {
      case this.tag[0]: {
        await this.getAlbum();
        break;
      }
      default: {
        //statements; 
        break;
      }
    }
  }

我想使用回调功能来解决问题,但我不知道如何。 基本上,我想完全完成第一部分,然后继续进行第二部分。

逻辑是调用第一部分,回调第二部分。 我非常感谢任何帮助。 谢谢你。

【问题讨论】:

  • 它已经从上到下执行了,那么问题是什么?你想等动画先结束吗(fadeMeOut 看起来像动画相关的类)

标签: angular


【解决方案1】:

在 Angular 中,您可以使用 async 和 await 关键字来实现回调功能。 async 用于声明包含一个或多个异步操作的函数,await 用于暂停函数的执行,直到特定的异步操作完成。

下面是一个示例,说明如何使用 async 和 await 在代码中实现回调功能

async doCallback() {
  if (this.componentRef) {
    this.componentRef.location.nativeElement.classList.add('fadeMeOut');
  }

  // Wait for the class list modification to complete
  await this.timeout(200);
  switch (value) {
    case this.tag[0]: {
      await this.getAlbum();
      break;
    }
    default: {
      //statements; 
      break;
    }
  }
}

timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

在上面的示例中,doCallback() 函数首先向 componentRef 元素添加一个类,然后它使用 await 使用 timeout(ms) 函数暂停函数的执行 200 毫秒。

【讨论】:

    猜你喜欢
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2015-06-23
    • 2014-12-26
    • 2013-08-12
    • 2014-06-11
    相关资源
    最近更新 更多