Benefit of defining service at ngOnInit rather at Constructor in Angular

233 Views Asked by At

I am aware some of the facts where ngOnInit() and constructor differ. also I have come across many examples where services are defined at ngOnInit() method rather in a constructor and vice-versa.

But using services at constructor level is not prohibited by Angular. If such is the case what benefit it drives in doing so when compared to defining services at ngOInit()?

Example:

 export class App implements OnInit{

 constructor(private userService: UserService){
     userService.getDetails();
 }

 ngOnInit(){
    userService.getDetails(); 
 }  
1

There are 1 best solutions below

0
On

The ngOnInit() hook is one of the Angular lifecycle hooks. The example you provided works as you noticed, but it is limited because you can't access any @Input() variable in the constructor. So your pattern won't work if you want to pass a parameter to your service function, that comes from an @Input() variable. As a good practice, always use ngOnInit() instead of the constructor for your components initializations because everything will always work fine, while the constructor pattern will not work for every use case.