Angular JS1.X Learning Notes 11 - Service

Posted by mike2098 on Thu, 11 Jul 2019 23:23:49 +0200

If I remember correctly, spring has a service layer inside. What is service? Personal understanding is a tool that can be used in many places, across controllers and even modules. Angular JS also provides us with a service mechanism, which allows us to define something that is not unique to a controller as a service, which we can take directly when we need it. What are the benefits of using services? One is to facilitate uniform modification, the other is that the caller does not care about the internal implementation, and the third is to facilitate testing.

I. factory

  

<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
    <meta charset="UTF-8">
    <title>factory</title>
</head>
<body>
    <div ng-controller="dayCtrl"></div>
    <div ng-controller="secondCtrl"></div>

    

    <script type="text/javascript" src="../node_modules/angular/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module("myApp",[]);
        myApp.controller('dayCtrl',function($scope,logService){
            logService.log("dayCtrl exec");

        })
        .factory('logService',function(){
            var messageCount = 0;
            return {
                log: function(msg){
                    console.log("LOG"+messageCount++ +":"+msg);
                }
            }
        })
        .controller("secondCtrl",function(logService){
            logService.log("secondCtrl exec");
        })
    </script>
</body>
</html>

In this example, we create a service using the factory method, which accepts two parameters. The first one represents the name of the service and the second one is a factory function, which returns an object and exposes the method of the service in the object. Note that services are singular, and that's why the services above can be counted correctly. The method of invoking custom services is the same as that of invoking built-in services. Dependency injection is also used.

II. service

The use of service differs from the factory method in that its second parameter is a constructor (or constructor).

  

<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
    <meta charset="UTF-8">
    <title>service</title>
</head>
<body>
    <div ng-controller="dayCtrl"></div>
    <div ng-controller="secondCtrl"></div>

    

    <script type="text/javascript" src="../node_modules/angular/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module("myApp",[]);
        function BaseLogger(){
            this.messageCount = 0;
            this.log = function(msg){
                console.log(this.messageType+":"+this.messageCount++ +":"+msg);
            }
        }

        function DebugLogger(){};
        DebugLogger.prototype = new BaseLogger();
        DebugLogger.prototype.messageType="Debug";

        function ErrorLogger(){};
        ErrorLogger.prototype = new BaseLogger();
        ErrorLogger.prototype.messageType = "Error";

        myApp.controller('dayCtrl',function($scope,logService){
            logService.log("dayCtrl exec");

        })
        .service("logService",DebugLogger)
        .service("errorService",ErrorLogger)
        .controller("secondCtrl",function(errorService){
            errorService.log("secondCtrl exec");
        })
    </script>
</body>
</html>

In fact, service can also be used as a facrory

  

<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
    <meta charset="UTF-8">
    <title>factory</title>
</head>
<body>
    <div ng-controller="dayCtrl"></div>
    <div ng-controller="secondCtrl"></div>

    

    <script type="text/javascript" src="../node_modules/angular/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module("myApp",[]);
        myApp.controller('dayCtrl',function($scope,logService){
            logService.log("dayCtrl exec");

        })
        .service('logService',function(){
            var messageCount = 0;
            return {
                log: function(msg){
                    console.log("LOG"+messageCount++ +":"+msg);
                }
            }
        })
        .controller("secondCtrl",function(logService){
            logService.log("secondCtrl exec");
        })
    </script>
</body>
</html>

 

There is no problem in doing so.

III. provider

The provider approach allows you to better control the way service objects are created or configured.

  

<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
    <meta charset="UTF-8">
    <title>provider</title>
</head>
<body>
    <div ng-controller="dayCtrl"></div>

    

    <script type="text/javascript" src="../node_modules/angular/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module("myApp",[]);
        myApp
        .config(function(logServiceProvider){
            logServiceProvider.debugEnabled(false);
        })
        .controller('dayCtrl',function($scope,logService){
            logService.log("dayCtrl exec");

        })
        .provider('logService',function(){
            var debug = true;
            return {
                debugEnabled:function(setting){
                    if(angular.isDefined(setting)){
                        debug = setting;
                        return this;
                    }else{
                        return debug;
                    }
                },

                $get:function(){
                return {
                    messageCount:0,
                    log:function(msg){
                        if(debug){
                            console.log("LOG"+this.messageCount++ +":"+msg);
                        }
                        
                    }
                }
            }
        }

            
        })
    </script>
</body>
</html>

Provider is very powerful and can configure our services through config. The debugEnabled method is provided in the above example to configure whether to log or not. In essence, you can see from the source code that both service and factory methods are special forms of provider methods.

See, factory is the invoked provider and service is the invoked factory, so service and factory are both providers, and providers they can do can also do.

IV. Built-in Services

Here is a reference (see: http://www.cnblogs.com/best/p/6263915.html)

Send HTTP requests for $http

Create a RESTful server-side data source interaction object with $resource

jQuery wrapping of window elements in $windows browser

jQuery wrapping of document elements in $document browser

Access to $rootScope root scope

Access to the root element of $rootElement

$cacheFactory provides key/value pairs placed in object caches

$interval provides access to window.setInterval

$timeout provides access to window.setTimeout

$cookies provides read and write access to browser cookies

$animate provides animation hooks to link to both CSS and JavaScript-based animations

Well, that's all for services. Today we have to finish looking at ajax and routing. Come on! _

Topics: Javascript angular JQuery Spring