参考: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. apt-key adv

    gpg --recv-keys KEY-ID                gpg --armor --export KEY-ID | sudo apt-key add - http://m.blog ...

  2. java基础概念经典题目汇集

    1.下面是People和Child类的定义和构造方法,每个构造方法都输出编号.在执行new Child("mike")的时候都有哪些构造方法被顺序调用?请选择输出结果 ( ) cl ...

  3. JUST SORT

    We define B is a Divisor of one number A if A is divisible by B. So, the divisors of 12 are 1, 2, 3, ...

  4. Boyer Moore算法(字符串匹配)

    上一篇文章,我介绍了KMP算法. 但是,它并不是效率最高的算法,实际采用并不多.各种文本编辑器的"查找"功能(Ctrl+F),大多采用Boyer-Moore算法. Boyer-Mo ...

  5. Mesos架构简介

    1. 前言 同其他大部分分布式系统一样,Apache Mesos为了简化设计,也是采用了master/slave结构,为了解决master单点故障,将master做得尽可能地轻量级,其上面所有的元数据 ...

  6. Linux学习 -- 系统管理

    1 进程管理 判断服务器健康状态 top [选项] 查看系统中所有进程 ps aux      BSD格式 ps -le        Linux格式 pstree [选项] -p   显示PID - ...

  7. Linux 监控文件事件

    某些应用程序需要对文件或者目录进行监控,来侦测其是否发生了某些事件.Linux很贴心的为我们提供了inotify API,也是Linux的专有. inotify API 在使用之前一定要有一个inot ...

  8. Oracle 使用sql创建表空间及用户

    create tablespace OrcalDBNamedb datafile 'C:\OracleDBDirc\OrcalDBNamedb.dbf' size 300m; 创建用户create u ...

  9. hdu_3886_Final Kichiku “Lanlanshu”(数位DP)

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=3886 题意:这题的题意有点晦涩难懂,大概意思就是给你一个区间,让你找一些满足递增递减条件的数,举个列: ...

  10. hdu_4352_XHXJ's LIS(数位DP+状态压缩)

    题目连接:hdu_4352_XHXJ's LIS 题意:这题花大篇篇幅来介绍电子科大的一个传奇学姐,最后几句话才是题意,这题意思就是给你一个LL范围内的区间,问你在这个区间内最长递增子序列长度恰为K的 ...