DEV Community

Cover image for Angular: How I Broke ngOnInit
bob.ts
bob.ts

Posted on

2

Angular: How I Broke ngOnInit

So, recently I ran into an issue where one of my functions was not being implemented "at the correct time." The solution was to trigger it in another component via ngOnInit.

Moving the code was simple, but in the process I ran into an issue that I've seen before but not dug into.

The Problem

The issue is that I like to use fat-arrow functions in my code (() => {}) and somewhere along the way I converted an ngOnInit to fat-arrow. I unknowingly broke the OnInit lifecycle hook complete.

ngOnInit = async (): Promise<void> => {
  await this.init();
  ...
};
Enter fullscreen mode Exit fullscreen mode

The Resolution

The fix was actually pretty simple, I converted the code back to a traditional function pattern ...

async ngOnInit(): Promise<void> {
  await this.init();
  ...
}
Enter fullscreen mode Exit fullscreen mode

... and my function started working again.

Conclusion

Be careful (yes, I am telling myself this) as you may inadvertently write code that does not execute correctly. It was a simple mistake and one that was hidden by some layers of async behavior.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay