I am working on an angular app where I want to fetch data from REST API and display it on browser in the form of a graph. The issue is that the graph gets rendered as soon as the ngOnInit() gets initialized. I want to ask whether a .component.ts file gets executed first or .service.ts? Will it be okay if I fetch data in my .service.ts and then pass it to .component.ts to be displayed on the browser?
I understand your question, you're probably asking:
Does a service constructor get called before ngOnInit
in a component that depends on the service?
The answer is yes. The constructor is actually called the moment the service is first needed, that means the moment the component is first rendered, which may be much later than the application start (bootstrap).
Will it be okay if I fetch data in my .service.ts and then pass it to .component.ts to be displayed on the browser?
No, it won't be okay, because as mentioned above, the service will start loading the data the moment it is contructed, but the data will not be there yet, because the operation is asynchronous.
You need to wait for the data in the component. If you're using HttpClient, you can do it using observables.
//service.ts
loadData() {
return this.http.get<Response>('/data/path')
}
//component.ts
ngOnInit() {
this.service.loadData().subscribe(
data => this.processData(data),
error => this.error = error
)
}
private processData(data: DataResponse) {
this.data = data;
this.renderChart();
}
Asynchronous data processing is a key concept to frontend programming and explaining how that all works goes beyond a single StackOverflow answer. I suggest readers follow a few tutorials on Angular Http, RxJS, API communication or asynchronocity in general.