Angular 5-将数据存储在服务中而不是组件中? [英] Angular 5 - storing data in the service instead of the component?

查看:87
本文介绍了Angular 5-将数据存储在服务中而不是组件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AngularJS 1.5应用程序中,我有一些控制器数据直接链接到服务数据。当用户点击页面时,控制器调用服务中的init,然后调用数据服务以从服务器中检索数据。

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.

Eg

//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);
   }

}

我正在努力将应用程序迁移到Angular 5,我想要类似的功能。

I am working on moving the app to Angular 5 and I would like the similar functionality.

这种类型的事情如何在Angular 5中实现?
是将数据放入组件或服务中的最佳实践吗?

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?

推荐答案

仅应将组件负责向DOM显示数据或对用户交互做出反应。最好将所有休息都委派给服务。

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.

p>

对于您的特定情况,您应该在Component内部调用服务方法。可以通过将服务作为依赖项注入到Component类中来完成。

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.

因此,假设在您的方案中,您有一个名为的服务。 ClockingDataService ,而您的 ClockingMenuComponent 依赖于 ClockingDataService 来获取数据,您可以在 ClockingDataService 中公开方法 getClockingDataFromServer ,并从ClockingMenuComponent的方法中调用该方法,该方法应该对 startWeek endWeek

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.

为简单起见,我ve使AppComponent模拟 ClockingMenuComponent ngOnInit 模拟函数处理程序以更改 startWeek 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.

这里是 StackBlitz 供您参考。

这篇关于Angular 5-将数据存储在服务中而不是组件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆