[AngularJS] --13 Service Service

There are many services in AngularJS, the commonly used such as $ http, $ location, and so on.

This article will explain the contents:

  1 $ http use the service provided by this Angular

  2 How to customize services and service summary to note a few small points.

  Use the $ http

  AngularJS provides us with a variety of services, $ http for sending http requests, dynamic requests data.

  This will require the use of web container to run code, take a look at the program source code, or aspects of the same view with the ordinary code:

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

  Create an unordered list request to the cycle of the output data.

  In js, create a template, create a controller on the template.

<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>

  The controller of controllers than usual ordinary one more injection parameters $ http, add this parameter, you can directly call the internal methods.

  The format is as follows:

$http({
  method:'GET',//http请求的类型
  url:'data.json'//请求的地址
}).success(function(data,status,headers,config){
  //成功了,怎么做
}).error(function(data,status,headers,config){
  //失败了,怎么做
});

  Next we need under the same code path, file creation data.json

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

  Using a web container, as used herein, it is based nodejs of http-server, after starting to enter the appropriate URL in a web page to see the results:

  All code shows:

<!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

 

  Use $ http content is very basic, not do too much explanation.

  Create your own Service Service

  Then take a look at how to create your own service, you can create a service in three ways, Factory's, Provider and Service , but their essence is the Provider, but encapsulates the different ways of writing it.

  In this paper, in the form of factory still is to create a module, create a Service Module on the basis of:

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);
                    }
                }
            }]);

  Analysis Code:

  The Service needs to inject a property  $ HTTP  , within the method, the return value of a method is provided externally, userList.

  External by  userList (username)  , the calling mode.

  The true realization on the part  doRequest  , the interior is typical of a AngularJS of $ http request, the request will return url corresponding data.

  Then look at how external use, take a look at the view part:

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

  The input section is an input box code box and a pre, they jointly use a variable username. When the username has a value, it will display the contents corresponding to users below.

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);
                        }
                    });
                }
            ]);

  In the corresponding controllers, using a $ Watch this monitoring method, monitoring username property changes. When the username property changes triggered request method.

  The controller of a multi-injection $ timeout variable, which is used to control the time of entry. Observation Code $ timeout (function (...), 350); when the input interval exceeds 350ms, the corresponding function will trigger function (...) . This can effectively prevent, stop the refresh request, refresh the page causing jitter.

  Inside the function, call our own services provided userList method. When the request succeeds, the return value to bind users in. users dynamically refreshed content.

  View demo program results:

  Test found that: When we fast input 4321, although $ watch are monitored changes in variables, but only stopped for more than 350ms before sending the request.

  All code samples:

<!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

 

  About custom services, there is need to pay attention to the following points:

  1 its use scenarios : a common extraction method since in the service invoked, the same functionality can be extracted out of the plurality of controllers, a service form.

  2 Singleton : Singleton services are of an application life cycle, there is only one instance of the service.

  3 injector : Example of services are all created injector injector. When we create controller controller, pointed out the need to inject a back myService service, the injector will go to instantiate the service.

  reference

  [1] desert poor demand, Mu class network: http: //www.imooc.com/learn/156

Reproduced in: https: //my.oschina.net/u/204616/blog/545165

Guess you like

Origin blog.csdn.net/weixin_34348174/article/details/91990155