Angular 5 - storing data in the service instead of

2019-08-23 11:02发布

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?

1条回答
混吃等死
2楼-- · 2019-08-23 11:40

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 your ClockingMenuComponent is dependent on the ClockingDataService to get the data, you can expose a method getClockingDataFromServer in your ClockingDataService and call it from your ClockingMenuComponent's method that is supposed to react to changes in the startWeek and endWeek.

For simplicity's sake, I've make the AppComponent to mock the ClockingMenuComponent and ngOnInit to mock the function handler for changes to the startWeek and endWeek.

Here's a StackBlitz for your reference.

查看更多
登录 后发表回答