如果一个角有服务状态? [英] Should an Angular service have state?

查看:125
本文介绍了如果一个角有服务状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,一些同事和我有一个讨论,以AngularJS服务是否应该具有的状态或没有。我们想出了一些赞成和反对它,我想获得关于这个问题更多的想法和反馈。在我的搜索,我发现但似乎没有要任何明确BEST-实践提及。在没有客户端的世界服务不应该保持状态,但我开始认为这是可以接受的客户端,因为它是一个不同的问题。

Recently some co-workers and I were having a discussion as to whether or not AngularJS services should have state or not. We came up with some arguments for and against it and I wanted to get additional thoughts and feedback on the subject. In my searching I found this but there doesn't seem to be any clear best-practice mentioned. In the none client-side world a service should never hold state, but I am starting to think that it might be acceptable client-side because its a different problem.

为保持状态服务的原因:


  1. 该服务不会被多个线程访问。每个浏览器都将拥有自己的服务的一个实例。

  2. 允许服务持有国家只关心它存放在rootScope约来代替。封装

原因服务无法保持状态:


  1. 服务不再幂等。调用函数可能会改变状态,因此基于服务的状态时调用它可能有不同的结果。

  2. 我认为,总体这将是更容易测试。

这是可能的的服务保持状态一节中解决#2将是对包含应用程序的当前状态rootScope设置APPSTATE对象的一个​​方法。然后,所有国家将在一个位置收集,然后你只是拉你需要什么了它在你的服务。我发现这个,不知道

One way that might address #2 in the "for services holding state" section would be to have an appState object set on the rootScope that contains the current state of the application. Then all the state would be gathered in one location and then you just pull what you need out of it in your service. I found this and wondered

推荐答案

在AngularJS,服务的通过工厂函数传递。基本上他们是可以包含一些状态的对象(例如,对于需要执行自己的行为缓存或存储数据)。

In AngularJS, services are passed in via factory function. And basically they are objects that can contain some state (e.g. for caching or storing data needed for performing their actions).

这可以有两个缺点一个很好的解决方案/没有状态是当服务(这可能是实际函数)包含状态返回的对象。

One good solution that can take both cons of having/not having state is when service (that could be actually function) that return object that contain state.

看看在 $ HTTP 服务:你可以得到这个服务调用的实例

Take a look at the $http service: you can get instance of this service calling

var x = $http({url:'...'});

和再由

var result = x.get() //actually `$http.get` is shortcut of this operation

ngResource 一样的:使用服务你与可以执行所需的操作,一些州的对象

Same with ngResource: using service you get object with some state that can perform desired actions.

所以基本上我认为这是最好的选择:从一个点你避免'副作用'通过移动可以通过行动统一到单独的对象,而不是存储在服务本身进行修改的状态,但可有特定状态的对象能够存储定义信息(例如身份验证信息等)。

So basically I think that is the best option: from one point you avoid 'side effects' by moving state that could be modified by actions into separate object, not stored in service itself, but can have specific state in that object to be able to store custom info (like auth information etc).

这篇关于如果一个角有服务状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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