Can anyone please tell me what will happen if I don't implement onInit interface and still using ngOnInit component lifecycle inside a component?
Since I used ngOnInit lifecycle hook without implementing an interface and it's worked for me the same.
So just wanted to understand why I should implement an interface?
We import OnInit in order to use it, implementing OnInit is not mandatory but considered good practice): import {Component, OnInit} from '@angular/core'; We use ngOnInit to do something after the component has been created. for example you can set variables here, call methods etc.
Angular will automatically call this when it initializes our component but we use implement OnInt interface to add compile time checking, so when we define implement OnInit interface typescript ensures that we have a method called ngOnInit.
One of the most common use cases for ngOnInit , is to establish observable assignments to component fields. It's good practice to do this in the ngOnInit so that observables are initialized at a predictable time in the component lifecycle.
userData; }); Your code within the subscribe above will AUTOMATICALLY be re-executed every time the route parameters change. So there is no need to manually call ngOnInit again.
It will still work as expected.
Interface helps us to avoid spelling and syntax mistakes.
According to recomendations from Angular Style Guide
Lifecycle interfaces prescribe typed method signatures. Use those signatures to flag spelling and syntax mistakes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With