Angular使用根范围与服务共享数据 [英] Angular use root scope vs services to share data
本文介绍了Angular使用根范围与服务共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在阅读 wrox angular book 。在本书中,作者描述了一种在控制器之间共享数据的方法是
I have been reading wrox angular book. Inside the book the author describes that a method of sharing data between controllers is to
- 在根范围内拥有一个属性
- 更新根作用域上的该属性
- 广播该属性已更新的事实
- 需要知道的所有子作用域,将听取广播。
- Have a property on the root scope
- Update that property on the root scope
- Broadcast the fact that the property was updated
- All children scopes that need to know , will listen for the broadcast.
而不是在服务上公开一个对象并让角度的双向数据绑定完成所有繁重的工作。为什么有人会使用'根范围发布/订阅'方法,而不是在服务上公开对象?
as opposed to expose an object on a Service and letting angular's two way databinding do all the heavy lifting. Why would anyone go with the 'root scope publish/subscribe' methodology, instead of exposing an object on the service?
推荐答案
那是有趣的问题。
首先我们应该考虑不同层面的差异:
First we should consider differences on various levels:
-
范围
Scope
- 如果是
$ rootScope
我们在全局范围内定义变量 - 如果是共享服务,我们可以将此服务注入真正使用此值的控制器
- in case of
$rootScope
we define variable in global scope - in case of shared services we can inject this service to controllers that really use this value
可扩展性
-
$ rootScope
- 我们添加额外逻辑的选项有限处理这个值(我们可以定义另一个全局函数) - 共享服务 - 我们可以自由定义任何类型的逻辑
$rootScope
- we have limited options to add additional logic to work on this value (we can define another global function)- shared services - we are free to define any kind of logic
封装
-
$ rootScope
- $ rootScope中定义的所有对象将在所有模块中可见 - shared服务 - 我们可以决定什么是可见的,什么不是
$rootScope
- all object defined in $rootScope would be visible in all modules- shared services - we can decide what is visible and what is not
模块化
-
$ rootScope
- 全局变量不在模块空间中的位置 - 共享服务 - 服务是一个单独的申请模块
$rootScope
- global variables is not places in module spaces- shared services - service is a separate module for application
维护
-
$ rootScope
- 很难找到哪些组件使用我们的$ rootScope
变量。 - 共享服务 - 我们可以看到我们使用哪些服务,我们可以找到我们使用此服务的组件
$rootScope
- it's very hard to find which components use our$rootScope
variable.- shared services - we can see which services we use and we can find in which component we use this service
绑定
-
$ rootScope
- 很容易在$ rootScope
- 共享服务中的一个变量上的几个控制器中设置双向绑定 - 启用双向可能很棘手绑定
$rootScope
- it is easy to setup two-way binding in several controllers on one variable in$rootScope
- shared services - could be tricky to enable two-way binding
在我看来,这只适用于制作真正的全局变量。
In my opinion this is only useful for make really global variables.
这篇关于Angular使用根范围与服务共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文