Angular 使用根范围与服务来共享数据 [英] Angular use root scope vs services to share data

查看:24
本文介绍了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

  1. 在根范围内有一个属性
  2. 在根范围更新该属性
  3. 广播该属性已更新的事实
  4. 所有需要知道的子作用域都会监听广播.

与在服务上公开一个对象并让 angular 的双向数据绑定完成所有繁重的工作相反.为什么有人会采用根范围发布/订阅"方法,而不是在服务上公开对象?

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:

  • 范围

  • $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 中定义的所有对象在所有模块中都可见
  • 共享服务 - 我们可以决定什么是可见的,什么是不可见的
  • $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
  • 中的一个变量上的多个控制器中设置双向绑定
  • 共享服务 - 启用双向绑定可能很棘手

在我看来,这仅对制作真正的全局变量有用.

In my opinion this is only useful for make really global variables.

这篇关于Angular 使用根范围与服务来共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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