angular學習(四)—— Services__angular

來源:互聯網
上載者:User

來源地址: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的Factory 方法來定義services。 
services的Factory 方法可以返回一個單例對象或者函數。該對象或函數可以任意注入到依賴於該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的Factory 方法,只有當被調用時才會進行執行個體化。

Dependencies

services也可以有自己的依賴,就像在controller中聲明依賴一樣,services可以在他的Factory 方法中聲明依賴。 
下面的樣本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.資料的標識符的順序和Factory 方法中的順序是一致的。

用$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的依賴關係

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.