This could be tagged opinion based. But I am looking for standard/best-practise. I am building an Angular 2 application and I have to manipulate the data from the API before I show it in the template. For example, if my service looks like:
getData(id: number): Observable<Data> {
return this.http
.get(this.url + '/' + id)
.map((res) => {
return res.json().data;
});
}
prepareData(data) {
// manipulate and return the data
}
And on my component, I could call the service like this:
getData(id: number): void {
this.dataService.getData(id)
.subscribe((data: Data) => {
this.showData = this.dataService.prepareData(data)
};
}
But is this the standard approach? Or should the prepareData
function be included in the component instead?
Another way to phrase it is, should the service be heavy when compared to components or should it be light and only act as an interface to get the data?
Simple, generic transformations everyone will need (such as
res => res.json().data
) should go in the service.View-specific transformations that depend on presentation logic (such as
data => data.user.firstName + ' ' + data.user.lastName
) should go in your components.The service should be able to provide data without knowing what will be rendered. The Component should be able to render data without knowing where it came from.