Angularjs registering and using services and constants (provider, factory, service, constant, value)

Source: Internet
Author: User
Tags builtin

1. Introduction

The ANGULARJS employs an MVC architecture that provides a mechanism for registering services and using services in a dependency injection manner. A service is an abstraction of a function (method) and data (constant), such as a system in which information about a user's information (avatar, nickname, signature, birthday, gender, etc.) is abstracted and focused on an object, then the object can be considered a service. Services are available through angular. Module (often obtained as var app = Angular.module (' My-app ', []) and $provider (acquired by dependency Injection) object, often used in a dependency injection manner.

Each service has a (string type) name, which is provided at registration, and the dependency injection subsystem obtains the service object through the service name. Services are singleton, so every service you get is the same service object.

The following is a simple example of how to register and use the service in code, and a pit that may be encountered (dependency injector $injector cannot find the service error: [$injector: UNPR] Unknown provider:xxxxxx. By looking at the source Code discovery Angular Registration service will automatically add the suffix "Provider" after the service name, I have encountered a dependency injector dead or alive can not find the corresponding service name, after I went to the dependency injection variable name after manually adding Provider after the successful run, but this problem can not be reproduced, and therefore cannot be explained. This example is simple enough to show that the service (and data) is registered in 5 ways (provider, factory, service, constant, value) registered through the service, and then gets the service and data through a dependency injection, which is then displayed on the Web page.

Of the 5 ways, the latter 4 are dependent on the provider approach, and 5 are more specific, less flexible, and therefore easier to register.

2. Provider mode

The common invocation form for the provider registration service is:

varApp = Angular.module (' app ', []); App.provider (' Starprovider ',function() {Console.log (' Provider Constructor ')    //The $get function must be defined     This. $get =function() {Console.log (' Provider $get func ')        varCounter = 0; varobj =function () {        }; Obj.favorite=function () {            return' Michelle Reis x ' + counter++;        }; returnobj; }});

The emphasis in the provider function is the second argument, which must define the $get function, which becomes the getter function that gets the service object.

3. Factory mode

Factory method registration, formally similar to provider, different is that the second parameter is a factory function, the function is a return value of the function, the return value is the service object, angular in the implementation of Factory mode, is to pass the factory second argument as the $get property of a new object to provider as its second argument.

The code form is usually:

function () {    console.log (' factory constructor ')    var c = 0;     var fac = {};        // Define a service object first, and then define its service interface    function () {        return ' Rosamund Kwan X ' + C + +;    }; return FAC;});
4. Service mode

The factory-to-service specialization program is similar to the second parameter provider to Factory,service does not use the factory pattern in factory, and the second parameter is the constructor for the service object, where the public property defined is the service interface of the service. As you can see, unlike the factory approach, service mode no longer defines the Services object (the FAC variable in the previous example) in the second parameter (the executable object) because it is the service object itself. The code that registers the service in this manner often appears in the following form:

function () {    console.log (' service constructor ')    var c = 0;      This function () {        // often define the service interface in This.xxx        return ' Lan Jie x ' + C + +;    }})
5. Constant, Value method

These two methods are used to register constants (constant amount, not necessarily a string or numeric type), the difference is small, and is not often used by me, an unknown solution, the form of registration code is:

App.constant (' starconstant ', ' Chingmy Yau-const '); App.value (' Starvalue ', ' Anita Mui-val ');
6. How to use the service (Dependency injection)
Three types of Dependency injection usage: Anonymous, inline, display claims, all three ways to first declare the angular built-in service (the name typically starts with $). All custom provider services (provider, factory, service) are automatically added with the "provider" suffix when they are registered (three of all, not provider add provider, Factory Add factory, service Add service).
1. Inferred Dependency Injection: The parameter name must be the same as the service name, angular to infer the service that needs to be injected
app. Provider (' This-service-name ',function($http, $scope, Myotherservice) {})
2. Inline: Form: [' $builtIn 1 ',' $builtIn 2 ',' MyOtherService1 ',function(Builtin1alias, Builtin2alias,myotherservice1alias) {}]
app. Provider (' This-service-name ', [' $builtIn 1 ',' $builtIn 2 ',' MyOtherService1 ',function(Builtin1alias, Builtin2alias,myotherservice1alias) {}])
3. Display the declaration. The $inject array that declares the dependency to the object.varFoo=function(){};Foo.$inject= [' $builtIn 1 ',' $builtIn 2 ',' MyOtherService1 ']
app. Factory (' Starfactory ',Foo)
7. Example effects and code

The effect is as follows:

The code compression package is here on the network disk.

Angularjs registering and using services and constants (provider, factory, service, constant, value)

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.