目录[-]

一、service引导

刚开始学习Angular的时候,经常被误解和被初学者问到的组件是 service(), factory(), 和 provide()这几个方法之间的差别。This is where we'll start the twenty-five days of Angular calendar.

二、service

在Angular里面,services作为单例对象在需要到的时候被创建,只有在应用生命周期结束的时候(关闭浏览器)才会被清除。而controllers在不需要的时候就会被销毁了。

这就是为什么使用controllers在应用里面传递数据不可靠的原因,特别是使用routing的时候。Services are designed to be the glue between controllers, the minions of data, the slaves of functionality, the worker-bees of our application(就是说services在应用的controllers、 方法、数据之前起到了很关键的作用)

现在我们开始看怎么创建service。每个方法我们都会看到下面两个一样的参数:

  • name-我们要定义的service的名字

  • function-service方法

他们都创建了相同的底层对象类型。实例化后,他们都创建了一个service,这些对象没有什么功能上的差别。

1、factory()

Angular里面创建service最简单的方式是使用factory()方法。

factory()让我们通过返回一个包含service方法和数据的对象来定义一个service。在service方法里面我们可以注入services,比如 $http 和 $q等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
angular.module('myApp.services')
.factory('User'function($http) { // injectables go here
  var backendUrl = "http://localhost:3000";  var service = {    // our factory definition
    user: {},
    setName: function(newName) { 
      service.user['name'] = newName; 
    },
    setEmail: function(newEmail) {
      service.user['email'] = newEmail;
    },
    save: function() {
      return $http.post(backendUrl + '/users', {
        user: service.user
      });
    }
  };  return service;
});
  • 在应用里面使用factory()方法

在应用里面可以很容易地使用factory ,需要到的时候简单地注入就可以了

1
2
3
4
angular.module('myApp')
.controller('MainCtrl'function($scope, User) {
  $scope.saveUser = User.save;
});
  • 什么时候使用factory()方法

在service里面当我们仅仅需要的是一个方法和数据的集合且不需要处理复杂的逻辑的时候,factory()是一个非常不错的选择。

注意:需要使用.config()来配置service的时候不能使用factory()方法

2、service()

service()通过构造函数的方式让我们创建service,我们可以使用原型模式替代javaScript原始的对象来定义service。

和factory()方法一样我们也可以在函数的定义里面看到服务的注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
angular.module('myApp.services')
.service('User'function($http) { // injectables go here
  var self = this// Save reference
  this.user = {};
  this.backendUrl = "http://localhost:3000";
  this.setName = function(newName) {
    self.user['name'] = newName;
  }
  this.setEmail = function(newEmail) {
    self.user['email'] = newEmail;
  }
  this.save = function() {
    return $http.post(self.backendUrl + '/users', {
      user: self.user
    })
  }
});

这里的功能和使用factory()方法的方式一样,service()方法会持有构造函数创建的对象。

  • 在应用里面使用service()方法

1
2
3
4
angular.module('myApp')
.controller('MainCtrl'function($scope, User) {
  $scope.saveUser = User.save;
});
  • 什么时候适合使用service()方法

service()方法很适合使用在功能控制比较多的service里面

注意:需要使用.config()来配置service的时候不能使用service()方法

3、provider()

provider()是创建service最底层的方式,这也是唯一一个可以使用.config()方法配置创建service的方法

不像上面提到的方法那样,我们在定义的this.$get()方法里面进行依赖注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
angular.module('myApp.services')
.provider('User'function() {
  this.backendUrl = "http://localhost:3000";
  this.setBackendUrl = function(newUrl) {
    if (url) this.backendUrl = newUrl;
  }
  this.$get = function($http) { // injectables go here
    var self = this;
    var service = {
      user: {},
      setName: function(newName) {
        service.user['name'] = newName;
      },
      setEmail: function(newEmail) {
        service.user['email'] = newEmail;
      },
      save: function() {
        return $http.post(self.backendUrl + '/users', {
          user: service.user
        })
      }
    };
    return service;
  }
});
  • 在应用里面使用provider()方法

为了给service进行配置,我们可以将provider注入到.config()方法里面

1
2
3
4
angular.module('myApp')
.config(function(UserProvider) {
  UserProvider.setBackendUrl("http://myApiBackend.com/api");
})

这样我们就可以和其他方式一样在应用里面使用这个service了

1
2
3
4
angular.module('myApp')
.controller('MainCtrl'function($scope, User) {
  $scope.saveUser = User.save;
});
  • 什么时候使用provider()方法

  1. 当我们希望在应用开始前对service进行配置的时候就需要使用到provider()。比如,我们需要配置services在不同的部署环境里面(开发,演示,生产)使用不同的后端处理的时候就可以使用到了

  2. 当我们打算发布开源provider()也是首选创建service的方法,这样就可以使用配置的方式来配置services而不是将配置数据硬编码写到代码里面。

还可以看看这篇翻译:http://www.oschina.net/translate/top-10-mistakes-angularjs-developers-make

点击查看完整的代码:https://gist.github.com/auser/7743235

AngularJS中service,factory,provider的区别(转载:http://my.oschina.net/tanweijie/blog/295067)的更多相关文章

  1. AngularJS进阶(三十三)书海拾贝之简介AngularJS中使用factory和service的方法

    简介AngularJS中使用factory和service的方法 AngularJS支持使用服务的体系结构"关注点分离"的概念.服务是JavaScript函数,并负责只做一个特定的 ...

  2. angularjs---服务(service / factory / provider)

    初angularJs时  常写一些不够优雅的代码  !我总结了一下看看各位有没有中枪的!-----( 这里只针对服务service及其相关! ) 以下做法不太优雅 兄弟controller 之间的相同 ...

  3. AngularJS 中的 factory、 service 和 provider区别,简单易懂

    转自:http://blog.csdn.net/ywl570717586/article/details/51306176 初学 AngularJS 时, 肯定会对其提供 factory . serv ...

  4. AngularJS中service,factory,provider的区别

    一.service引导 刚开始学习Angular的时候,经常被误解和被初学者问到的组件是 service(), factory(), 和 provide()这几个方法之间的差别.This is whe ...

  5. AngularJS之Provider, Value, Constant, Service, Factory, Decorator的区别与详解

    本文转载自http://camnpr.com/javascript/1693.html 首先,provider, value, constant, service, factory他们都是provid ...

  6. AngularJS中的指令全面解析(转载)

    说到AngularJS,我们首先想到的大概也就是双向数据绑定和指令系统了,这两者也是AngularJS中最为吸引人的地方.双向数据绑定呢,感觉没什么好说的,那么今天我们就来简单的讨论下AngularJ ...

  7. 简介AngularJS中使用factory和service的方法

    AngularJS支持使用服务的体系结构“关注点分离”的概念.服务是JavaScript函数,并负责只做一个特定的任务.这也使得他们即维护和测试的单独实体.控制器,过滤器可以调用它们作为需求的基础.服 ...

  8. angularjs model.service vs provider vs factory?

    <!DOCTYPE html> <html ng-app="app"> <head> <script src="http://c ...

  9. angular 服务 service factory provider constant value

    angular服务 服务是对公共代码的抽象,由于依赖注入的要求,服务都是单例的,这样我们才能到处注入它们,而不用去管理它们的生命周期. angular的服务有以下几种类型: 常量(Constant): ...

随机推荐

  1. 【转】MYSQL入门学习之六:MYSQL的运算符

    转载地址:http://www.2cto.com/database/201212/175862.html 一.算术运算符 1.加  www.2cto.com           mysql> s ...

  2. easyui enableFilter combobox级联 combotree

    //网格过滤         function datagridFilter(dg){             dg.datagrid('enableFilter');             dg. ...

  3. Unity帧序列实时渲染脚本

    该脚本会创建一个新相机进行录制,支持包含所有相机内容,完美解决跳帧问题,可自定义分辨率等参数,脚本会输出品质为100的jpg序列,基本无损. 但缺点是帧率始终是每秒100帧,必须压制时限制帧数. 而用 ...

  4. Scrapy学习教程

    http://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/tutorial.html 在线学习教程: http://learnpythonthehardway ...

  5. muduo库安装

    一.简介 Muduo(木铎)是基于 Reactor 模式的网络库. 二.安装 从github库下载源码安装:https://github.com/chenshuo/muduo muduo依赖了很多的库 ...

  6. zoj Abs Problem

    Abs Problem Time Limit: 2 Seconds      Memory Limit: 65536 KB      Special Judge Alice and Bob is pl ...

  7. c++中两种常量方法的比较

    [c++]在C++中定义常量的两种方法的比较   常量是定以后,在程序运行中不能被改变的标识符.C++中定义常量可以用#define .const 这两种方法.例如: #define PRICE 10 ...

  8. WebForm跨页面传值---内置对象

    一.Response Response - 响应请求对象 string path = "Default2.aspx": (1)Response.Redirect(path); -- ...

  9. cetos6.5安装Tomcat

    一. 下载Tomcat 官网下载Tomcat  tar.gz文件 二. 解压tar.gz文件 tar -zxvf tomcat.tar.gz 三. 在catalina.sh最上面添加一下内容 expo ...

  10. python学习笔记六 初识面向对象上(基础篇)

    python面向对象   面向对象编程(Object-Oriented Programming )介绍   对于编程语言的初学者来讲,OOP不是一个很容易理解的编程方式,虽然大家都知道OOP的三大特性 ...