Calling async method in ngInit not working in Angular 14

78 Views Asked by At

I have a problem with calling an “async” method in “ngInit” method in angular 14 here is the method I want to call when component initialized:

async setInterfaceDatatableHeaders() {
    var bankName = await GetTranslatedValue(this.translate, "SUPPLIERMANAGEMENT.Bank”)
      .then(res => {
        return res;
      });
    var accountOwnerName = await GetTranslatedValue(this.translate, "GENERAL.AccountOwnerName”)
      .then(res => {
        return res;
      });
    var interfaceBankID = await GetTranslatedValue(this.translate, "SUPPLIERMANAGEMENT.InterfaceBankID”)
      .then(res => {
        return res;
      });
    var accountOwnerTel = await GetTranslatedValue(this.translate, "GENERAL.AccountOwnerTel”)
      .then(res => {
        return res;
      });

    this.interfaceDatatableHeaders = [
      new DataTableHeaderDTO('BankName', bankName, 'text'),
      new DataTableHeaderDTO('AccountOwnerName', accountOwnerName, 'text'),
      new DataTableHeaderDTO('InterfaceBankID', interfaceBankID, 'text'),
      new DataTableHeaderDTO('AccountOwnerTel', accountOwnerTel, 'text'),
    ]
  }

When I call it directly in ngInit, method not calling and not working but if I surround the method with a “setTimeout” function, it will work properly

This works :

setTimeout(async () => {
      await this.setInterfaceDatatableHeaders();
    }, 0);

This NOT work with this way of calling, even if I set async for my “ngInit” method:

await this.setInterfaceDatatableHeaders();

How can I fix this without using “setTimeout” in “NgInit” ???

0

There are 0 best solutions below