ANGULARJS Custom Services

Source: Internet
Author: User

In Angularjs, the services built into the system begin with the service $ , so our custom services are avoided as much as possible $ . There are several ways to customize a service:

    • Provider method for using module
    • Factory method for using module
    • Service methods using the module

Using the Provider method

function () {    thisfunction  () {            //dosomthing    } ;});

A service created by the provider method must contain a $get method, and the result of the provider injection is the $get result of the method return, and if the method is not included $get , the program will error.

Of the three methods of creating services, only services created using the provider method can be passed into the CONFIG function to configure the module before the object is enabled. However, configuration in config can only be a $get variable defined outside the function, in the provider defined below only artist with thingFromConfig two variables can be accessed, and getArtist getThingFromConfig two methods cannot be accessed in the config function.

And in the injection of the CONFIG function, the parameter name must be 服务名+Provider composed of, for example, the following example injected into the myProviderProvider config function is

App.controller (' Myctrl ', [' $scope ', ' MyProvider ',function($scope, MyProvider) {Console.log (Myprovider.getthingfromconfig ()); //Kingx name }]); App.provider (' MyProvider ',function () {      This. Artist = ";  This. Thingfromconfig = ";  This. $get =function () {         varthat = This; return{getartist:function () {                 returnthat.artist; }, Getthingfromconfig:function () {                 returnThat.thingfromconfig; }         }     }; }); App. Config (function(Myproviderprovider) {//Note the name of the parameter here Myproviderprovider.thingfromconfig= ' Kingx name '; });
Using the Provider method  
function ($http) {       // not necessarily object type, actually any type       var factory = {};        return factory;   });

A service created through the factory method must have a return value, that is, a return function, which can return any type of value, including the base data type or object type. If there is no return function , an error occurs.

The result of the factory injection is the result of the return returned , which can be used to define various methods of the injected result in the injected object.

1App.controller (' Myctrl ', [' $scope ', ' myfactory ',function($scope, myfactory) {2Console.log (Myfactory.getname ());//Foo3      //request test.html under the current folder4Myfactory.getdata ('./test.html '). Then (function(response) {5Console.log (response);//returns the string form of the test.html6      });7  }]);8 9  /**------------Use the factory method-----------------*/TenApp.factory (' MyFactory ',function($http) { One      varFactory = {}; A      var_name = ' foo '; -      //emulating Ajax requests -Factory.getdata =function(URL) { the          return$http ({ -Method: ' Get ', - Url:url -          }); +      }; -  +Factory.getname =function () { A          return_name; at      }; -  -      returnfactory;//Return here is factory contains 2 methods -});

Using the Service method   

A service created with the service method can not return any value, because the service method itself returns a constructor, and the system uses the New keyword to create an object, so we can use the This keyword inside the service to extend the service.

1App.controller (' Myctrl ', [' $scope ', ' MyService ',function($scope, MyService) {2 Console.log (myservice);3Myservice.setname (' foo '));4 Console.log (Myservice.getname ());5     }]);6 7     /**------------Use the service method-----------------*/8App.service (' MyService ',function () {9          This. _name = ";Ten  One          This. GetName =function () { A             return  This. _name; -         }; -  the          This. SetName =function(name) { -              This. _name =name; -         }; -  +});

If you use a notation with a return value, the value returned must be an object , and if only the base type is returned, the actual return is the equivalent of this

1App.service (' MyService ',function () {2      varobj = {};3       This. _name = ";4 5Obj.getname =function () {6          return  This. _name;7      };8 9Obj.setname =function(name) {Ten           This. _name =name; One      }; A      returnobj; -});

Comparison of three different methods
    • If you need to configure global configuration in config, you can only select the provider method
    • Factory and service are the methods used to create services more frequently. The only difference between them is that the service method used to inject the result is usually the new object, and the result of the factory method injection is usually a series of functions
    • Provider is the most complex way to create a service, unless you need to create a reusable piece of code and need to be globally configured to use provider to create
    • All objects that have a specific purpose are created by means of the factory method.

ANGULARJS Custom Services

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.