【AngularJS】—— 13 服務Service

來源:互聯網
上載者:User

標籤:

在AngularJS中有很多的服務,常用的比如$http,$location等等。

本篇文章會介紹一下的內容:

  1 $http這種Angular提供的服務的使用

  2 如何自訂服務,並總結服務需要注意的幾個小點。

  $http的使用

  AngularJS為我們提供了很多種服務,$http用於發送http請求,動態請求資料。

  這樣就需要使用web容器來運行代碼了,先看看程式源碼,視圖方面還是跟普通的代碼相同:

<div ng-controller="myAppCtrl">            <ul>                <li ng-repeat="user in users">                    {{user.name}}                </li>            </ul>        </div>

  建立一個無序列表,迴圈輸出請求到的資料。

  在js中,建立一個模板,在模板上建立控制器。

<script type="text/javascript">            var myAppModule = angular.module("myApp",[]);            myAppModule.controller(‘myAppCtrl‘,[‘$scope‘,‘$http‘,function($scope,$http){                $http({                    method:‘GET‘,                    url:‘data.json‘                }).success(function(data,status,headers,config){                    console.log("success!...");                    console.log(data);                    $scope.users = data;                }).error(function(data,status,headers,config){                    console.log("error!...");                });            }]);        </script>

  該控制器比平時普通的控制器多了一個注入的參數$http,添加了這個參數,就可以在方法內部直接調用。

  採用如下的格式:

$http({  method:‘GET‘,//http請求的類型  url:‘data.json‘//請求的地址}).success(function(data,status,headers,config){  //成功了,怎麼做}).error(function(data,status,headers,config){  //失敗了,怎麼做});

  接下來需要在代碼相同的路徑下,建立data.json檔案

[{    "name":"test1"},{    "name":"test2"},{    "name":"test3"}]

  利用web容器,本文使用的是基於nodejs的http-server,啟動後在網頁中輸入相應的URL查看結果:

  全部的代碼展示:

<!doctype html><html ng-app="myApp">    <head>         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />         <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>    </head>    <body>                <div ng-controller="myAppCtrl">            <ul>                <li ng-repeat="user in users">                    {{user.name}}                </li>            </ul>        </div>        <script type="text/javascript">            var myAppModule = angular.module("myApp",[]);            myAppModule.controller(‘myAppCtrl‘,[‘$scope‘,‘$http‘,function($scope,$http){                $http({                    method:‘GET‘,                    url:‘data.json‘                }).success(function(data,status,headers,config){                    console.log("success!...");                    console.log(data);                    $scope.users = data;                }).error(function(data,status,headers,config){                    console.log("error!...");                });            }]);        </script>    </body></html>
View Code

 

  使用$http是很基本的內容,就不做過多的解釋了。

  建立自己的Service服務

  接下來看看如何建立自己的服務,建立服務可以通過三種方式,factory,provider和service,但是它們的本質都是Provider,只是封裝了不同的寫法而已。

  本文採用factory的形式,仍然是先建立一個模組,在模組的基礎上建立一個Service:

var myAppModule = angular.module("myApp",[]);            myAppModule.factory(‘myService‘,[‘$http‘,function($http){                var doRequest = function(username){                    return $http({                        method:‘GET‘,                        url:‘data.json‘                    });                }                return {                    userList:function(username){                        return doRequest(username);                    }                }            }]);

  分析下代碼:

  這個Service需要注入一個屬性 $http ,在方法內部,返回的值是一個對外提供的方法,userList。

  外部可以通過 userList(username) 的方式,進行調用。

  真正的實現部分放在 doRequest 中,內部就是典型的一個AngularJS的$http請求了,請求會返回url相應的資料。

  然後看一下外部如何使用,先看看視圖部分:

        <div ng-controller="myAppCtrl">            <label>username</label>            <input type="text" ng-model="username" placeholder="輸入"/>            <pre ng-show="username">                {{users}}            </pre>        </div>

  該部分是一個輸入框input和一個代碼框pre,他們共同使用了一個變數username。當username有值時,會在下面展示users對應的內容。

myAppModule.controller(‘myAppCtrl‘,[‘$scope‘,‘$timeout‘,‘myService‘,                function($scope,$timeout,myService){                    var timeout;                    $scope.$watch(‘username‘,function(newUserName){                        console.log("您輸入了:"+newUserName);                        if(newUserName){                            if(timeout){                                $timeout.cancel(timeout);                            }                            timeout = $timeout(function(){                                myService.userList(newUserName).success(function(data){                                    console.log(data);                                    $scope.users = data;                                });                            },350);                        }                    });                }            ]);

  在對應的控制器中,採用了$watch這種監控方法,監控username屬性的變化。當username屬性變化時,會觸發要求方法。

  控制器多注入了一個$timeout變數,該變數用於控制輸入的時間。代碼觀察$timeout(function(...),350);當輸入的間隔超過350ms時,就會觸發相應函數function(...)。這樣可以有效防止,不停的重新整理請求,造成網頁的重新整理抖動。

  在函數內部,調用了我們自己的服務提供的userList方法。當請求成功時,綁定傳回值到users中。users會動態重新整理內容。

  查看程式的示範結果:

  通過測試發現:當我們快速的輸入4321時,雖然$watch都監控到了變數的變化,但是只有停止時間超過350ms才會發送請求。

  全部的代碼範例:

<!doctype html><html ng-app="myApp">    <head>         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />         <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>    </head>    <body>                <div ng-controller="myAppCtrl">            <label>username</label>            <input type="text" ng-model="username" placeholder="輸入"/>            <pre ng-show="username">                {{users}}            </pre>        </div>        <script type="text/javascript">            var myAppModule = angular.module("myApp",[]);            myAppModule.factory(‘myService‘,[‘$http‘,function($http){                var doRequest = function(username){                    return $http({                        method:‘GET‘,                        url:‘data.json‘                    });                }                return {                    userList:function(username){                        return doRequest(username);                    }                }            }]);            myAppModule.controller(‘myAppCtrl‘,[‘$scope‘,‘$timeout‘,‘myService‘,                function($scope,$timeout,myService){                    var timeout;                    $scope.$watch(‘username‘,function(newUserName){                        console.log("您輸入了:"+newUserName);                        if(newUserName){                            if(timeout){                                $timeout.cancel(timeout);                            }                            timeout = $timeout(function(){                                myService.userList(newUserName).success(function(data){                                    console.log(data);                                    $scope.users = data;                                });                            },350);                        }                    });                }            ]);        </script>    </body></html>
View Code

 

  關於自訂的服務,有下面幾點需要注意:

  1 它的使用情境:由於可以在服務中抽取公用調用的方法,因此可以把多個控制器中相同的功能抽取出來,形成一個服務。

  2 單例:服務都是單例的,一個應用生命週期內,只有一個服務的執行個體存在。

  3 注入器:服務的執行個體化都是有注入器injector建立的。在我們建立controller控制器時,後面指明了需要注入一個myService服務,注入器就會去執行個體化該服務。

  參考

  [1] 大漠窮求,慕課網:http://www.imooc.com/learn/156

【AngularJS】—— 13 服務Service

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.