I have come across recommendations stating that server requests should be made via services and not components in order to ensure reusability of functions by other components. Ultimately, the server response is needed in the component.
My query pertains to the best practice for making a call from the component to the service to retrieve data. I am concerned because HTTP requests are handled asynchronously using Observables.
If I were to do something like this:
//data.component.ts
const data = this.httpService.getDataFromTheServer();
//httpService.service.ts
getDataFromTheServer(){
return this.http.post(url).map(
res=>res.json())
}
The data does not populate in the component's variable.
My solution to this issue is using another "Subject" as follows:
//data.component.ts
this.httpService.getDataFromTheServer()
this.httpService.getData.subscribe(res => {
const data = res;
}
//httpService.service.ts
public getData = new Subject();
getDataFromTheServer(){
return this.http.post(url).map(
res=> this.getData.next(res.json()))
}
While this works fine, I am unsure if it's the best practice. Does anyone have any alternative ideas? Thank you!
UPDATE
Thank you to all who responded. I now understand that in my component, I can use:
this.httpService.getDataFromTheServer().subscribe...
But I am curious if there is a way to streamline my components further and make do with just:
const data = this.httpService.getDataFromTheServer()
Is there another method to simplify the components or did I misunderstand the recommendation to "make server requests via services"? I would appreciate further clarification.