In my AngularJS 1.5 app I have some controller data that directly links to the service data. When the user hits the page, the controller calls init in the service and then a data service is called to retrieve the data from the server.
E.g.
//inside controller
$scope.data = ClockingMenuService.data;
ClockingMenuService.init();
//inside service
function ClockingMenuService() {
var dataObj = {};
var defaultData = {
startWeek: null,
endWeek: null,
statusCode: 0
};
Object.assign(dataObj, defaultData);
return {
data: dataObj,
};
function init() {
ClockingDataService
.getClockingDataFromServer(dataObj.startWeek, dataObj.endWeek)
.then(function(response) { dataObj = response; })
.catch(handleError);
}
}
I am working on moving the app to Angular 5 and I would like the similar functionality.
How could this type of thing be implemented in Angular 5? Is it best practice to put the data in the component or in the service?
A component should only be responsible for showing data to the DOM or react to User Interactions. Rest all should ideally be delegated to a service. The Component should have a minimum to no knowledge of where the service is going to get the data from.
This is how it would have a better separation of concerns.
For your specific case, you should be calling a service method inside a Component. That can be done by injecting the service into the Component class as a dependency.
So let's say that in your scenario, you have a service named
ClockingDataService
, and yourClockingMenuComponent
is dependent on theClockingDataService
to get the data, you can expose a methodgetClockingDataFromServer
in yourClockingDataService
and call it from your ClockingMenuComponent's method that is supposed to react to changes in thestartWeek
andendWeek
.For simplicity's sake, I've make the AppComponent to mock the
ClockingMenuComponent
andngOnInit
to mock the function handler for changes to thestartWeek
andendWeek
.Here's a StackBlitz for your reference.