DEV Community

Discussion on: Forcing Angular to Wait on Your Async Function

Collapse
 
titomoi profile image
TitoMoi

Another example, in this case to block the template render is:

//myclass.component.ts

class myClass() ... {

 data = undefined;

  async ngOnInit() {
    this.data = await myService.myFunction();
  }
}
Enter fullscreen mode Exit fullscreen mode

//myclass.component.html

<ng-template *ngIf="data">
...
</ng-template>
Enter fullscreen mode Exit fullscreen mode

or use resolvers, but I think this is less code and less hard.

Collapse
 
jdgamble555 profile image
Jonathan Gamble

That will not always work. ngOnInit is NOT an async function even with async, which is why I wrote this article. It will NOT wait for the function to complete. It just allows you to use the await keyword, but it is not an async function, despite having the async keyword. The function may or may not complete in time.

Collapse
 
titomoi profile image
TitoMoi

true, is not async in fact, but this works because await is queuing the call, is like:

ngOnInit()
... some time later...
myFunction resolves and data is populated, so the template is unblocked.

This is like a "hack" and confusing but works because the template has to wait the data.

This scenario is not a default one, blocking the template is not a good practice but in some scenario like the init of an app maybe fits and is not necessary to use Factories.

Thread Thread
 
jdgamble555 profile image
Jonathan Gamble • Edited

The problem is that it is not guaranteed to be resolved before the component is initialized because it is not a REAL async function. Using zone.js will guarantee it gets resolved before the component is loaded. Any other function with async in front of it, IS a real async function. Yes, it is a hack, but sometimes there is no other way.