参考: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. 初次stack-overflow 提交答案

    初次在stack-overflow上面提交答案,首先编辑器非常好用,语法检查都有, 还有付费版的,更高级,更好用,nice. 付费版:https://www.grammarly.com/upgrade ...

  2. auto_ash

    #!/usr/bin/ksh ##############paramter######################startdate=$1' 00:00:01'enddate=$2' 23:59: ...

  3. OpenGL------在Windows系统中显示文字

    增加了两个文件,showline.c, showtext.c.分别为第二个和第三个示例程序的main函数相关部分.在ctbuf.h和textarea.h最开头部分增加了一句#include <s ...

  4. linux视频学习6(mysql的安装/)

    1.mysql的优点: 免费,跨平台,轻,支持多并发. 2.mysql的安装步骤: 把安装文件准备好,拷贝到home目录下.mount /mnt/cdrom cp mysql* /home 把安装文件 ...

  5. json对象的简单介绍

    1.JSON(JavaScript Object Notation)一种简单的数据格式,比xml更轻巧.JSON是JavaScript原生格式,这意味着在JavaScript中处理JSON数据不需要任 ...

  6. 图像操作相关 With Quartz 2D

    本文将为大家介绍常见的IOS图像处理操作包括以下四部分:旋转,缩放,裁剪以及像素和UIImage之间的转化,主要使用的知识是quartz2D.Quartz2D是CoreGraphics框架中的一个重要 ...

  7. SwiftDate 浅析

    SwiftDate是Github上开源的,使用Swift语言编写的NSDate封装库,可以很方便的在Swift中处理日期,比如日期创建,比较,输出等. 特性 支持数学运算符进行日期计算(比如myDat ...

  8. Android ViewDragHelper完全解析 自定义ViewGroup神器

    Android ViewDragHelper完全解析 自定义ViewGroup神器   转载请标明出处: http://blog.csdn.net/lmj623565791/article/detai ...

  9. java int和Integer的区别

    今天偶然和同学讨论到int和Integer的区别是,发现自己对这个问题了解的并不是很清楚,而且有些概念还是错的,所以在这对int和Integer的区别做一个总结. int与integer的区别从大的方 ...

  10. python 第三方库下载

    C:\Python27\Scripts 路径下: easy_install.exe: C:\Python27\Scripts>easy_install.exe pycrypto pip.exe: ...