Home > Web Front-end > JS Tutorial > Detailed explanation of custom services in AngularJS, introduction to the usage of factory, service and provider

Detailed explanation of custom services in AngularJS, introduction to the usage of factory, service and provider

寻∝梦
Release: 2018-09-08 15:06:18
Original
1462 people have browsed it

This article mainly talks about the introduction of custom services of angularjs. Some specific usage examples of custom services. Now let’s take a look at this article

Preface

  1. 3 ways to create custom services.

    1. Factory

    2. Service

    3. Provider

  2. Everyone should know that AngularJS was invented by backend staff in their spare time. He mainly applied the layered thinking that already existed in the backend. So we have to understand the role of layering. If you are a front-end person and don’t understand what layering is, then you’d better ask your back-end colleagues.
    dao layer: It is the Model layer. When in the background, the role of this layer is to write the layer that interacts with the database. In angularJS, it is mainly used to write ajax.
    Service layer: It mainly checks and writes logic code, but it can also persist data (acting as a data container) in angularJS for use by different controllers.
    controller layer: The control layer, where controllers are written in angularJS. Try not to write unnecessary logic in the controller, and try to write it in the service layer.
    So, there are three ways to create custom services.

1.factory

The service created by factory method is to return a An object whose properties have methods. Equivalent to: var f = myFactory();

<!DOCTYPE html><html><head><meta charset="utf-8"><script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script></head><body><p ng-app="myApp" ng-controller="myCtrl">
    <p>{{r}}</p></p><script>
    //创建模型
    var app = angular.module(&#39;myApp&#39;, []);    //通过工厂模式创建自定义服务
    app.factory(&#39;myFactory&#39;, function() {
        var service = {};//定义一个Object对象&#39;
        service.name = "张三";        var age;//定义一个私有化的变量
        //对私有属性写getter和setter方法
        service.setAge = function(newAge){
            age = newAge;
        }
        service.getAge = function(){
            return age; 
        }        return service;//返回这个Object对象
    });    //创建控制器
    app.controller(&#39;myCtrl&#39;, function($scope, myFactory) {
        myFactory.setAge(20);
        $scope.r =myFactory.getAge();
        alert(myFactory.name);
    });</script></body></html>
Copy after login

In a custom serviceInject service example, but $scope scope objects cannot be injected.

<script>    var app = angular.module(&#39;myApp&#39;, []);
    app.factory(&#39;myFactory&#39;, function($http,$q) {
        var service = {};
        service.name = "张三";        //请求数据
        service.getData = function(){
            var d = $q.defer();            $http.get("url")//读取数据的函数。
            .success(function(response) {
                d.resolve(response);
            })
            .error(function(){
                d.reject("error");
            });            return d.promise;
        }       
        return service;
    });
    app.controller(&#39;myCtrl&#39;, function($scope, myFactory) {
        //alert(myFactory.name);
        myFactory.getData().then(function(data){
            console.log(data);//正确时走这儿
        },function(data){
            alert(data)//错误时走这儿
        });;
    });
</script>
Copy after login

2.service

Create a custom service through service method, which is equivalent to an object of new: var s = new myService() ;, only properties and methods added to this can be called in the controller. (If you want to see more, go to the PHP Chinese website AngularJS Development Manual to learn)

<p ng-app="myApp" ng-controller="myCtrl">
    <h1>{{r}}</h1></p><script>
    var app = angular.module(&#39;myApp&#39;, []);

    app.service(&#39;myService&#39;, function($http,$q) {
        this.name = "service";        this.myFunc = function (x) {
            return x.toString(16);//转16进制
        }        this.getData = function(){
            var d = $q.defer();
            $http.get("ursl")//读取数据的函数。
                .success(function(response) {
                d.resolve(response);
            })
                .error(function(){
                alert(0)
                d.reject("error");
            });            return d.promise;
        }
    });
    app.controller(&#39;myCtrl&#39;, function($scope, myService) {
        $scope.r = myService.myFunc(255);
        myService.getData().then(function(data){
            console.log(data);//正确时走这儿
        },function(data){
            alert(data)//错误时走这儿
        });
    });</script>
Copy after login

3.provder

Only provider is a service that can pass the .config() function. If you want to perform module-wide configuration before the service object is enabled, you should choose provider. It should be noted that when injecting the provider in the config function, the name should be: providerName Provider.
The advantage of using Provider is that you can use the Provider object in the app.config function before passing it to other parts of the application. to modify.
When you create a service using a Provider, the only properties and methods that can be accessed in your controller are the content returned by the $get() function.

<body><p ng-app="myApp" ng-controller="myCtrl"></p><script>
    var app = angular.module(&#39;myApp&#39;, []);    //需要注意的是:在注入provider时,名字应该是:providerName+Provider   
    app.config(function(myProviderProvider){
        myProviderProvider.setName("大圣");       
    });
    app.provider(&#39;myProvider&#39;, function() {
        var name="";        var test={"a":1,"b":2};        //注意的是,setter方法必须是(set+变量首字母大写)格式
        this.setName = function(newName){
            name = newName  
        }        this.$get =function($http,$q){
            return {
                getData : function(){
                    var d = $q.defer();
                    $http.get("url")//读取数据的函数。
                        .success(function(response) {
                            d.resolve(response);
                        })
                        .error(function(){
                            d.reject("error");
                        });                    return d.promise;
                },                "lastName":name,                "test":test
            }   
        }

    });
    app.controller(&#39;myCtrl&#39;, function($scope,myProvider) {
        alert(myProvider.lastName);
        alert(myProvider.test.a)
        myProvider.getData().then(function(data){
            //alert(data)
        },function(data){
            //alert(data)
        });
    });</script></body>
Copy after login

4. Inject custom services into the filter

<body><p ng-app="myApp">
    在过滤器中使用服务:    <h1>{{255 | myFormat}}</h1></p><script>
    var app = angular.module(&#39;myApp&#39;, []);
    app.service(&#39;hexafy&#39;, function() {
        this.myFunc = function (x) {
            return x.toString(16);
        }
    });
    app.filter(&#39;myFormat&#39;,[&#39;hexafy&#39;, function(hexafy) {
        return function(x) {
            return hexafy.myFunc(x);
        };
    }]);</script></body>
Copy after login

This article ends here (if you want to see more, just Go to the PHP Chinese website AngularJS User Manual to learn). If you have any questions, you can leave a message below.

The above is the detailed content of Detailed explanation of custom services in AngularJS, introduction to the usage of factory, service and provider. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template