[英]Does it make sense to use angular services with es6 modules?
Does it make sense to use angular-services when we use ES6 modules? 使用ES6模块时使用角度服务是否有意义? For example we need a singleton module (
userService
) in our code and we can do like this: 例如,我们的代码中需要一个单独的模块(
userService
),我们可以这样做:
var app = angular.module('app', []);
app.service('userService', function(){
this.users = ['John', 'James', 'Jake'];
});
app.controller('FooController', ['$scope', 'userService', function($scope, userService){
console.log(userService);
}]);
But we can define the service in separate file: 但我们可以在单独的文件中定义服务:
/* ./user-service.js */
export default users = ['John', 'James', 'Jake'];
, then make the code like this: ,然后像这样编写代码:
var app = angular.module('app', []);
var userService = require('./user-service')
app.controller('FooController', ['$scope', function($scope){
console.log(userService);
}]);
and result will be absolutely the same as with services using. 和结果将与使用的服务完全相同。 So why use angular services when we can use modules?
那么为什么在我们可以使用模块时使用角度服务?
Yes! 是! It makes perfect sense.
这很有道理。
Services implement a particular responsibility in your application, moving data between the data store and views. 服务在您的应用程序中实现特定的责任,在数据存储和视图之间移动数据。
Modules allow you to organize your code and separate sections with different responsibilities. 模块允许您组织代码并分离具有不同职责的部分。
By putting each service into a module, you make it easier to browse and test your code. 通过将每个服务放入模块,您可以更轻松地浏览和测试代码。 It's easy to find all of the code that implements a responsibility.
很容易找到实现责任的所有代码。
Source: Difference between service, directive and module =) 来源: 服务,指令和模块之间的差异 =)
From my own personal notes (mostly snippets from the docs, google group posts, and SO posts): 从我自己的个人笔记 (主要是来自文档的片段,谷歌小组帖子和SO帖子):
Modules 模块
Services 服务
Directives (some of the items below say essentially the same thing, but I've found that sometimes a slightly different wording helps a lot) 指令 (下面的一些项目基本上是相同的,但我发现有时候略有不同的措辞有很多帮助)
Define and group Angular things (dependency injection stuff) in modules. 在模块中定义和分组Angular事物(依赖注入事物)。
Share data and wrap web server interaction in services. 共享数据并在服务中包装Web服务器交互。
Extend HTML and do DOM manipulation in directives. 扩展HTML并在指令中执行DOM操作。
And make Controllers as "thin" as possible. 并使控制器尽可能“薄”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.