In the Angular documentation, there is the following tip about code in a component constructor (second paragraph emphasized by me):
Call it in
ngOnInit
While you could call
getHeroes()
in the constructor, that's not the best practice.Reserve the constructor for simple initialization such as wiring constructor parameters to properties. The constructor shouldn't do anything. It certainly shouldn't call a function that makes HTTP requests to a remote server as a real data service would.
Instead, call
getHeroes()
inside thengOnInit
lifecycle hook and let Angular callngOnInit
at an appropriate time after constructing a HeroesComponent instance.
What about for services? Is it also bad to have an HTTP call (just the launch of an async request where the Observable
is stored locally) in the constructor? Services don't have an ngOnInit()
event, so what would the best practice for Services be?
Constructor in Angular is put into use to inject dependencies into the component class. It creates a new instance of the class when the compiler calls 'new MyClass ()'. While calling 'new MyClass()', it is vital that the exact match of the parameter passes the Angular component constructor of the class.
The constructor is a method in JavaScript and is considered as a feature of the class in es6 . When the class is instantiated it immediately runs the constructor whether it is used in Angular framework or not.So it is called by JavaScript engine and Angular has no control on that.
HttpRequest represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a HttpRequest , the clone method should be used.
I bet that you can find some examples of where constructor can be used with no harm but as a rule of thumb and best practice use "angular constructor" for it aka ngOnInit
lifecycle hook.
Sometimes using constructor can be impossible or requires additional work. For example, you need to fetch data from backend using service because if @Input()
data. Inputs are not bound during javascript object construction, but they are available in ngOnInit
Moreover what if you want to unit test your component/service? You create new instance for every test (thus invoking a constructor) and you are making additional calls to mocked http backend, or even worst - to live one.
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