Use of Service, Factory and Provider in anjular and summary of creating objects in js

Keywords: angular

When learning the use of Service in anjular, we find that it has some connection with the way of creating objects in js. So we summarize the way of using Service, Factory and Provider in anjular and the way of creating objects in js.


First, summarize several ways of creating objects in js

1. factory mode

function createObject(username, password) { 
    var object = new Object(); //Equivalent to var object={};         
    object.username = username; object.password = password;
    object.get=function(){
        alert(this.username); //Equivalent to alert(a.username)
    } 
    return object; 
} 
var object = createObject("zhangsan", "123"); //This method does not use new as a direct call to a function
object.get(); //zhangsan 

Feature: Each object created creates a separate space for the method, which consumes more memory. Because the function createObject returns an object, an object is created directly without new.  


2. constructor

function Person(username, password) {
     //Before executing the first line of code, the js engine generates an object for us 
    this.username =username; this.password = password;
    this.getInfo = function() { 
        alert(this.username); 
    }
    //Here is a hidden return statement for returning previously generated objects 
    //Only in the case of new later will these two points be mentioned in the commentary 
} 
var person = new Person("zhangsan", "123");//You use new to get an object, otherwise the person's value will be undefuned 
person.getInfo(); //zhangsan

Features: Every object created opens up a separate space for the method; when instantiating the object, it must use new, so that this can point to the instantiated object, instead of this, it is equivalent to calling the function directly, and the resulting person is undefuned.


3. Combination of prototype and constructor

function Person(username,password) { 
    this.username = username; 
    this.password = password; 
} 
Person.prototype.getInfo = function() { 
    alert(this.username); 
} 
var p = new Person("lisi","123456"); //This approach includes the constructor approach, so creating objects requires the use of new 
p.getInfo();

Characteristic: Simple prototype method can not use parameters to transfer parameters. All objects share the same method, using this constructor, and creating objects requires new.

2. Three ways of creating services by anjularjs: service, factory and provider


1.service
(1)service is a service created by a constructor, which is usually used directly to manipulate data and define functions.
(2) The service () method is suitable for service with more functional control.
(3) Cannot config
(4) There is no instantiation when defining services, and the controller instantiates myService when calling it, and only once.

var myApp = angular.module("myApp",[]);
myApp.service("myService",function(){
    var data1="data1";
    this.data2="data2";
    this.getData1=function(){
        return data1;
    };
});
myApp.controller("myCtr1",["$scope","myService",function($scope,myService){
    $scope.getWay1=function(){
        console.log( myService.getData1() );
    };
    $scope.getWay2=function(){
        console.log( myService.data2 );
    };
}]);


<div ng-controller="myCtr1">
    <button ng-click="getWay1()"></button> //data1
    <button ng-click="getWay2()"></button> //data2
</div>

2.factory
(1) It is an injectable function. The difference between factory and service is that factory is a normal function and service is a constructor, so Angular uses the new keyword when calling service, while factory only calls the normal function when calling factory, so factory must return the object to get the corresponding value. And service can not return.
(2) Using Factory is to create an object, add attributes to it, and return the object. After you pass the service into the controller, the attributes in the object in the controller can be used through the factory.
(3) In service, factory() is a very good choice when all we need is a collection of methods and data and no complex logic.
(4) Like service, the injection type is instantiated once in the controller without instantiating the definition.

var app = angular.module('myApp', []);  
app.factory('myFactory', function() {  
    console.log('instance myFactory');  
    var factory = {};  
    var data1= "data1";  
    factory.data2 = "data2";  
    factory.getData1 = function() {  
        return data1;  
    };  
    return factory;  
});  
 
app.controller('myCtrl',["$scope","myFactory",function(){
    $scope.getWay1 = function() {  
        alert(myFactory.getData1());  
    };  
    $scope.getWay2= function() {  
        alert(myFactory.data2);  
    };  
}]);  


<div ng-controller="myCtrl">  
        <button ng-click="getWay1()">Button 1</button>   //data1
        <button ng-click="getWay2()">Button two</button>   //data2
</div>

factory can also return objects like this:

app.factory('myFactory', function() {  
    return {
        getWay1:functory(){
        },
        getWay2:functory(){
        }
    }  
});

3.provider
(1) Providers is the only service that you can pass in the. config() function. When you want to configure the module scope before the service object is enabled, you should use provider.
(2)provider is instantiated at definition time and once
(3)provider must have a $get method
 
[example 1]

var app = angular.module('myApp', []);
app.provider('testProvider', function(){
    console.log('instance testProvider');
    var f = function(name) {
        alert("Hello, " + name);
    };
    this.$get = function(){
        return f;
    };
});
 
app.controller('myCtrl1', function($scope, testProvider) {
    $scope.onclick1 = function() {
        testProvider("Ten cups");
    };
});
app.controller('myCtrl2', function($scope , testProvider) {
    $scope.onclick2 = function() {
        testProvider("provider: Ten cups");
    };
});


<div ng-controller="myCtrl1">
    <button ng-click = "onclick1()">Please click on me 1.</button> //Ten cups
</div>
<div ng-controller="myCtrl2">
    <button ng-click = "onclick2()">Please click on me 2.</button>
    //provider: ten.
</div>


[example two]

var app = angular.module('app', []);
app.provider('movie', function () {
    var version;
    return {
       setVersion: function (value) {
            version = value;
        },
        $get: function () {
            return {
                title: 'The Matrix' + ' ' + version
            }
        }
    }
});
 
app.config(function (movieProvider) {    //The name of the service defined in the config phase + Provider
    movieProvider.setVersion('Reloaded');
});
app.controller('ctrl', function (movie) {
    expect(movie.title).toEqual('The Matrix Reloaded');
});

 
Thank you for your communication and correction!
Thank you for sharing the reference materials:

http://blog.csdn.net/u012841667/article/details/52751222

https://segmentfault.com/a/1190000003096933


  
  
 




Posted by dawnrae on Mon, 10 Dec 2018 05:54:05 -0800