angular学习(四)—— Services

来源地址:http://blog.csdn.net/lastsweetop/article/details/51244041

Services简介

angular的services非常适合用依赖注入的方式将对象组合在一起,你能用services跨app去组合和分享你的代码。 
angular services有以下两个特点: 
1.延迟实例化——当有app的组件依赖它的时候才会去实例化。 
2.单例模式——app的组件调用services时,只会获得一个services工厂实例化后的引用。

Services使用

使用services很简单,你只需为app的组件增加依赖即可,angular的DI系统为了做剩下的事情。

useservices.html

<script src="../script/angular.min.js"></script>
<script src="script.js"></script>
<body ng-app="myServiceModule">
<div id="simple" ng-controller="MyController">
    <p>Let's try this simple notify service, injected into the controller...</p>
    <input ng-init="message='test'" ng-model="message" >
    <button ng-click="callNotify(message);">NOTIFY</button>
    <p>(you have to click 3 times to see an alert)</p>
</div>
</body>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

script.js

(function(angular) {
    'use strict';
angular.
    module('myServiceModule', []).
    controller('MyController', ['$scope', 'notify', function ($scope, notify) { $scope.callNotify = function(msg) { notify(msg); }; }]).
    factory('notify', ['$window', function(win) { var msgs = []; return function(msg) { msgs.push(msg); if (msgs.length == 3) { win.alert(msgs.join("\n")); msgs = []; } }; }]);
})(window.angular);
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

Services创建

开发者可以通过使用module注册services名称和services的工厂方法来定义services。 
services的工厂方法可以返回一个单例对象或者函数。该对象或函数可以任意注入到依赖于该services的组件中。

Services注册

services可以使用module API来注册,通常使用module 工厂 api来注册。

var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function() {
  var shinyNewServiceInstance;
  // factory function body that constructs shinyNewServiceInstance
  return shinyNewServiceInstance;
});
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

注意你注册的不是一个services实例,仅仅是一个services的工厂方法,只有当被调用时才会进行实例化。

Dependencies

services也可以有自己的依赖,就像在controller中声明依赖一样,services可以在他的工厂方法中声明依赖。 
下面的示例module有两个services,每个services有不同的依赖。

var batchModule = angular.module('batchModule', []);

/**
 * The `batchLog` service allows for messages to be queued in memory and flushed
 * to the console.log every 50 seconds.
 *
 * @param {*} message Message to be logged.
 */
batchModule.factory('batchLog', ['$interval', '$log', function($interval, $log) {
  var messageQueue = [];

  function log() {
    if (messageQueue.length) {
      $log.log('batchLog messages: ', messageQueue);
      messageQueue = [];
    }
  }

  // start periodic checking
  $interval(log, 50000);

  return function(message) {
    messageQueue.push(message);
  }
}]);

/**
 * `routeTemplateMonitor` monitors each `$route` change and logs the current
 * template via the `batchLog` service.
 */
batchModule.factory('routeTemplateMonitor', ['$route', 'batchLog', '$rootScope',
  function($route, batchLog, $rootScope) {
    return {
      startMonitoring: function() {
        $rootScope.$on('$routeChangeSuccess', function() {
          batchLog($route.current ? $route.current.template : null);
        });
      }
    };
  }]);
 
 
  • 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
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 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
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

1.batchLog services依赖于内置的$interval service和$log services。 
2.routeTemplateMonitor services依赖于内置的$route service和自定义的batchLog services。 
3.两个services都用数组来声明他们的依赖 
4.数据的标识符的顺序和工厂方法中的顺序是一致的。

$provide注册Services

你可以通过module的config函数中的$provide对象来注册services

angular.module('myModule', []).config(['$provide', function($provide) {
  $provide.factory('serviceId', function() {
    var shinyNewServiceInstance;
    // factory function body that constructs shinyNewServiceInstance
    return shinyNewServiceInstance;
  });
}]);
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

这种技术常用来在单元测试中模拟services的依赖关系

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular 2 Services by Sohail Salehi English | 6 Apr. 2017 | ISBN: 1785882619 | 311 Pages | EPUB/PDF (conv) | 12.39 MB Key Features Leverage the latest Angular 2 and ES2016 features to create services Integrate third-party libraries effectively and extend your app's functionalities Implement a real-world case study from scratch and level up your AngularJS skills Book Description A primary concern with modern day applications is that they need to be dynamic, and for that, data access from the server side, data authentication, and security are very important. Angular 2 leverages its services to create such state-of-the-art dynamic applications. This book will help you create and design customized services, integrate them to your applications, import third-party plugins, and make your apps perform better and faster. This book starts with a basic rundown on how you can create your own Angular 2 development environment. You will then use Bootstrap and Angular UI components to create pages. You will also understand how to use controllers to collect data and populate them into NG UIs. Later, you will then create a rating service to evaluate entries and assign a score to them. Next, you will create "cron jobs" in NG. We will then create a crawler service to find all relevant resources regarding a selected headline and generate reports on it. Finally, you will create a service to manage accuracy and provide feedback about troubled areas in the app created. What you will learn Sketch and create wire-frames for your project Use controllers to collect data and populate them into NG UIs Create a controller and the required directives to build a tree data structure Implement a logic to decide the relevancy of any given evidence Create a partially-AI service Build controllers to set the template for the report Collect, investigate, perform decision-making, and generate report in one big automated process

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值