Reputation: 545
I had started learning angular. I observed that API calls are doing within the ngOnInit. Why not inside the constructor as we are doing dependency Injection also there. I know that component will be completely getting loaded inside the onInit function. So, Is there any problem if we access/call api data in constructor before loading component, if so in which way it will be ?
Upvotes: 0
Views: 740
Reputation: 650
The constructor should be used for dependency injection and to create/init objects. It is JS engine calls constructor and not Angular.
The ngOnInit() method is a special lifecycle hook and give us a signal that Angular has finished initialising the component. ngOnInit() gives us a guarantee that bindings are available and allows you to invoke method calls. It’s a common practice to use ngOnInit to perform initialization logic even if this logic doesn’t depend on dependency injection, DOM or input bindings.
Upvotes: 2