参考:http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

https://www.pluralsight.com/blog/tutorials/angularjs-step-by-step-services

想法:定义一个 angular module 之后呢, 在许多的 controller 中会有一些公共的函数,或者是说在很多controller 中都要使用到的共同的方法,类似的逻辑其实是可以提取出来,进行封装。

这样,就抽象出来了 service 这样一个概念。

来继续深入理解一下,

1、到底什么是 service 呢?(what is a service ?)

抽象出来的service 是无状态的,将一些种类的方法封装成一个对象。

The type of service I'm talking about is typically stateless and encapsulates some sort of functionality。

2、为什么需要 service 呢?(why we need services ?)

In my previous post about AngularJS controllers, I spoke a bit about the need for separation of concerns in modern-day JavaScript applications, which are much more involved than those of a decade ago. With the amount of JavaScript needed in a modern-day application, the architecture of your JavaScript takes on much more importance. Two of the five SOLID principles of object oriented design are directly related to Services: the Single Responsibility Principle (SRP) and the Dependency Inversion Principle (DIP).

The single responsibility principle teaches that every object should have a single responsibility. If we use the example of a controller, it's responsibility is essentially to wire up the scope (which holds your models) to your view; it is essentially the bridge between your models and your views. If your controller is also responsible for making ajax calls to fetch and update data, this is a violation of the SRP principle. Logic like that (and other business logic) should instead be abstracted out into a separate service, then injected into the objects that need to use it.

This is where the Dependency Inversion Principle comes in. The DIP states that objects should depend on abstractions, not concretions. In languages like C# and Java, this means your objects depend on Interfaces instead of Classes. In JavaScript you could look at any parameter of any function (constructor function or otherwise) as an abstraction, since you can pass in any object for that parameter so long as it has the members on it that are used within that method. But the key here is the ability to use dependency injection - the ability to inject into other objects. This means that all of your controllers, directives, filters and other services should take in any external dependencies as parameters during construction. This allows you to have loosely coupled code and has the added benefit of making unit testing much easier.

Use factory if object definition syntax is preferable
app.factory('factory', function () {
...
return {
value: '...'
};
});

  

or it returns something that is not an object for some reason.

Use service if this syntax is preferable

app.service('service', function () {
this.value = '...';
});

  or it should return an object created with new from another constructor, e.g.

app.factory('factory', function () {
return new someConstructor();
});

  VS

app.service('service', someConstructor);

  A good use case for service is that you can seamlessly refactor existing controllers with controllerAs syntax to inherit from common service, in this case no this statements replacement is required, as shown here:

app.service('parentControllerService', function () {
this.value = '...';
}); app.controller('MainController', function (parentControllerService) {
angular.extend(this, parentControllerService);
}); app.controller('ChildController', function (parentControllerService) {
angular.extend(this, parentControllerService);
this.value = '!!!';
});

  

 

angularJS 系列(三)- 自定义 Service的更多相关文章

  1. 【AngularJS中的自定义服务service VS factory VS provider】---它们的区别,你知道么?

    在介绍AngularJS自定义服务之前,我们先来了解一下AngularJS~ 学过HTML的人都知道,HTML是一门很好的伪静态文本展示设计的声明式语言,但是,要构建WEB应用的话它就显得乏力了. 而 ...

  2. Android高效率编码-第三方SDK详解系列(三)——JPush推送牵扯出来的江湖恩怨,XMPP实现推送,自定义客户端推送

    Android高效率编码-第三方SDK详解系列(三)--JPush推送牵扯出来的江湖恩怨,XMPP实现推送,自定义客户端推送 很久没有更新第三方SDK这个系列了,所以更新一下这几天工作中使用到的推送, ...

  3. 转载:[AngularJS系列] 那伤不起的provider们啊~ (Provider, Value, Constant, Service, Factory, Decorator)

    来源:http://hellobug.github.io/blog/angularjs-providers/ 用AngularJS做项目,但凡用过什么service啊,factory啊,provide ...

  4. [AngularJS系列(4)] 那伤不起的provider们啊~ (Provider, Value, Constant, Service, Factory, Decorator)(转)

    用AngularJS做项目,但凡用过什么service啊,factory啊,provider啊,开始的时候晕没晕?!晕没晕?!感觉干的事儿都差不多啊,到底用哪个啊?!别告诉我你们几个就是为了跟我炫耀兄 ...

  5. VSTO之旅系列(三):自定义Excel UI

    原文:VSTO之旅系列(三):自定义Excel UI 本专题概要 引言 自定义任务窗体(Task Pane) 自定义选项卡,即Ribbon 自定义上下文菜单 小结 引言 在上一个专题中为大家介绍如何创 ...

  6. [angularjs] angularjs系列笔记(五)Service

    AngularJs中你可以使用自己的服务或使用内建服务,服务是一个函数或对象,以下代码试验$location服务,$http服务,$timeout服务,$intverval服务,创建自定义服务 < ...

  7. AngularJs创建自定义Service

    AngularJs可以创建自定义的service.下面的自定义service实现一个double倍数的服务: 参考下面语法: app.service('double', function () { t ...

  8. WCF编程系列(三)地址与绑定

    WCF编程系列(三)地址与绑定   地址     地址指定了接收消息的位置,WCF中地址以统一资源标识符(URI)的形式指定.URI由通讯协议和位置路径两部分组成,如示例一中的: http://loc ...

  9. AngularJS 系列 01 - HelloWorld和数据绑定

    目录导读: AngularJS 系列 学习笔记 目录篇 前言: 好记性不如烂键盘,随笔就是随手笔记,希望以后有用. 本篇目录: 1. Hello World 2. AngularJS中的数据绑定 3. ...

  10. Android总结篇系列:Android Service

    Service通常总是称之为“后台服务”,其中“后台”一词是相对于前台而言的,具体是指其本身的运行并不依赖于用户可视的UI界面,因此,从实际业务需求上来理解,Service的适用场景应该具备以下条件: ...

随机推荐

  1. fatal error: gst/gst.h

    ln命令使用 ln -s  源文件(src)  目标文件(dest) 进到这个文件:~/LowDA/sysroots/mx6q/usr/include$ ln -s gstreamer-0.10/gs ...

  2. TextUtils

    /** * 计算关键字在文本中出现的次数 * @param text * @param key * @return */ public static int count(String text, St ...

  3. 利用npoi把多个DataTable导入Excel多个sheet中

    { 题外拓展:把datatable插入dataset DataTable fuben = new DataTable();//定义的datatablefuben = table.Tables[0].C ...

  4. windows ORA-12560: TNS: 协议适配器错误

    1.first it report ORA-12560: TNS: 协议适配器错误 手工设定环境变量如下: set ORACLE_HOME=d:\app\OAadmin\product\11.2.0\ ...

  5. 【java】基础中的杂乱总结(一)

    1 构造代码块 作用:给对象进行初始化.对象一建立就运行,并且优先于构造函数执行 构造函数是给所有对象进行统一初始化,构造函数是给对应的对象初始化 package package1; class Pe ...

  6. windows下编译Android版本的boost库文件

    1.起因: 手上有一个用到了boost的asio库和thread库的工程要编译到手机上(Android版本和ios版本),本文只介绍如何编译到Android版本,ios版本之后再介绍,也许就不介绍了( ...

  7. HTML+CSS D08浮动

    1. <html> <head> <title>div浮动</title> <style type="text/css"> ...

  8. Hidden Word

    Hidden Word time limit per test 2 seconds memory limit per test 256 megabytes input standard input o ...

  9. Android OpenGL ES(四)关于EGL .

    OpenGL ES的javax.microedition.khronos.opengles 包定义了平台无关的GL绘图指令,EGL(javax.microedition.khronos.egl ) 则 ...

  10. JDBC 事务隔离级别

    JDBC 事务隔离级别     先解释一下:a:脏读取:一个事务读取了另外一个并行事务未提交的数据b:不可重复读取:一个事务再次读取之前的数据时得到的数据不一致,被另外一个事务修改c:虚读:一个事务重 ...