【问题标题】:Promise call gets invoked twice in Angular 11Promise 调用在 Angular 11 中被调用两次
【发布时间】:2021-04-09 06:49:06
【问题描述】:

我有下面的代码调用服务来获取一些值,我故意关闭后端部分以检查是否添加了错误。我注意到它会调用两次服务,有人可以解释一下为什么会这样吗?

(async () => {
      try {
        this.countries = await this.testerSvc.getCountries().toPromise();
      } catch (err) {
        this.addError("Countries");
      }
    })();

服务代码:

getCountries() {
    return this.http.get<[]>(this.baseUrl + "countries");
}

【问题讨论】:

  • 您将第一个 sn-p 中的代码具体放在哪里?
  • @Bergi 这在我组件的构造函数中。
  • 所以有些东西正在实例化该组件两次。但是,我建议避免将异步副作用放在构造函数中。
  • 找到了我的问题。我在 app.module.ts 的引导部分中添加了我的组件:引导:[AppComponent,MyComponent]。我从那里删除,现在它只进行一次服务调用。谢谢!

标签: promise es6-promise angular-promise


【解决方案1】:

在我的 app.module.ts 上我添加了我的组件:

bootstrap: [AppComponent, MyComponent]

在我的 app.component.html 上,我有

<app-tester> </app-tester>

它实例化了我的组件两次,我从引导程序中删除了它,现在它只实例化了一次。所以服务调用只有一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2020-09-23
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2012-05-05
    相关资源
    最近更新 更多