I am using angular 2 for fetching data from an API with an Injectable service written for it.Should I call my service in the constructor or ngoninit in the component where i am going to utilize my data. Can someone explain the best way to use constructor and ngoninit hook in angular 2 like constructor is used for instantiating services.
Asked
Active
Viewed 1,137 times
2 Answers
1
In my opinion you should call it in ngOnInit. First of all you have access to @Input's which is usually the case with services calling some api by http.
In terms of designs, constructor should only assign dependencies. There shouldn't be any logic inside. It increase testibility of a class as you don't have to set up additional stuff on object creation.

kit
- 4,890
- 3
- 24
- 23
1
The recommend way is defining the service in the constructor and call it in ngOnInit, for example:
constructor(private newsService: NewsService) {}
ngOnInit() {
this.newsService.method().....
}
Reference to: enter link description here
We use ngOnInit
for all the initialization/deceleration and avoid stuff to work in the constructor
. The constructor
should only be used to initialize class members but shouldn't do actual "work".