AngularJS--Provider (Providers)

Source: Internet
Author: User

Each Web application has multiple object combinations and collaboration to accomplish the task. These objects need to be instantiated and connected together to work. In ANGULARJS applications, these objects are instantiated and assembled automatically by the Injector injector service. In the case of the injector injector, it can create two types of objects: service services and special objects.

The special object is the API that complies with the specified angular framework. These objects can be either a controller or a directive instruction or a filter filter, or animation animation ... And our injector injector needs to know how to create these objects. Then you have to tell the injector exactly how to create it by registering a method for creating the object.

Our most common way to tell the injector how to create an object by registering is four: Value, Factory,service, Constant (constant). Let's take a look at how to create and use service services in different ways in different scenarios.

Note: In order for the Registrar injector to know how to create and assemble all these objects, it needs a registered list, a cookbook (list). Each object in the manifest has an identifier and a description of how to create the object. Each manifest element is a angular module. A angular module can also have one or more manifests, that is, a module can contain information about other modules that it says depend on.

A angular application starts with a startup module, and angular creates an instance of the injector injector first. In turn, create modules that angular their own cores (the "NG" module), and the modules they rely on to register with the injector injector list. After that, the Registrar injector can know how to create the object you want based on the information registered in its list list ...

Value list Element (= = person or custom call provider)

Suppose we want a very simple service called "clientId" that can provide a string of authentication information for a remote application API. You should define this:

var myApp = angular.module (' MyApp ', []); Myapp.value (' clientId ', ' a12345654321x ');

Note that we created a module called MyApp, which defines a checklist that specifies how to build the ClientID service, which is a string in the example.

Here's a look at how to use angular data binding to use the ClientID service we just defined.

<ng-app= "myApp"><ng-controller = "Democontroller as demo" >   Client ID: {{Demo.clientid}}</body></  HTML>//  ... js ... myapp.controller (' Democontroller ', [' clientId ', function Democontroller (clientId) {this.clientid = clientId;}]);

is not very simple, is not a look to understand. *^_^*

In this example, we use the value list element to define a service called ClientID, and when we use it in the controller, we tell the injector list that we need a service called ClientID, Then we get an example of this service. Of course, here, this service is just a string ....

Factory (Factory) manifest element (provider of a factory method)

The value manifest element is a very simple element, which is simply not enough when we create a service like this. So now it's time for our other powerful list elements to come up: Factory factory list elements. It has the following capabilities:

1. Can use other services (dependencies)

2. Initialize the service.

3. Delay/Lazy Loading

A factory manifest element that uses a function method (functions) that can have one or more parameters to configure how to create a new service. Its return value is that method, and it knows how to create the service you want.

Special Note : In the angular, all the services are single-case Oh!! That is, the injector will only create the object you call, and then when you create it again, it gives you a direct reference. And I'm not going to give it to you. Create a service instance ...

Because the factory factory manifest element is a very powerful provider, we can change the provider of our previous use of the value manifest element to create the ClientID service:

function clientidfactory () {return ' a12345654321x ';});

However, it is important to note that in our previous example, our ClientID is just a credential, in that case, the value provider is more appropriate for it. We are only here to demonstrate, to use the factory provider to achieve the following.

Let's discuss it again, for example, I can seafood create a service and also pull over to calculate a cryptographic token for remote authentication. This token is calculated by the value provided by our value provider just now, and by a data that we store locally in secret:

function apitokenfactory (clientId) {varfunction(data1, data2) {  //  Nsa-proof encryption algorithm:  return (data1 + ': ' + data2). toUpperCase ();}; var secret = Window.localStorage.getItem (' Myapp.secret '); var apitoken = encrypt (clientId, secret); return ApiToken;}]);

In the example above, we see how the ApiToken service is defined by the factory (Factory) provider, and it relies on the ClientID service. Its implementation is to return the data of our ClientID service and the data stored locally.

Recommendation: When defining a service, it is best to use the "factory" suffix, although not required, but this is very helpful for future debugging and use.

Service Manifest Element

JavaScript developers typically use custom types for object-oriented development. Let's take a look at the following example:

function Unicornlauncher (apitoken) {this. launchedcount = 0;  This function () {  // make a request to the remote API and include the ApiToken...   this. launchedcount++;}}

Please note that our unicornlauncher needs to be apitoken, and we can use the factory provider to meet Unicornlauncher's reliance on ApiToken services:

function (apitoken) {returnnew  unicornlauncher (ApiToken);}]);

is not feeling a bit awkward ah! The correct approach is to use the service provider to implement.

The process of service provider production and the value provider are similar to the factory factory provider, but it is a constructor called by the new operator. Of course, you can also pass in 0 or more parameters to represent the dependencies of other services on your service team.

Because we are going to give our unicornlauncher type a constructor, we can rewrite this in the way we used the factory factory provider in the example above:

Myapp.service (' Unicornlauncher ', ["ApiToken", Unicornlauncher]);

It's a lot easier!

Provider list elements

As described in the signature, the provider manifest element is a very core provider type, and all other manifest element (provider) types are a syntactic sugar on top of the provider manifest element, which is a wrapper. It's the strongest list element, but it's too powerful for most services.

The provider manifest element is syntactically a custom type that implements the $get method. It is a factory method similar to our factory factory manifest element. In fact, if you define a factory manifest element, an empty provider type and $get method will set your factory function according to the advanced options.

You can use the provider manifest element only when you want to expose a configuration API that can be made before your application starts. Generally not used, you can use it for application configuration when you need to make your two applications a little different.

Our Unicornlauncher service is really useful. By default, our initiators are not shielded when they are running. However, there are times when we have to do some protection when we start. This is very, very useful. If we do some protection before our launcher runs, it's very advantageous for your application, and we can configure it like this:

Myapp.provider (' Unicornlauncher ',functionUnicornlauncherprovider () {varUsetinfoilshielding =false; This. usetinfoilshielding =function(value) {usetinfoilshielding= !!value;}; This. $get = ["ApiToken",functionunicornlauncherfactory (apitoken) {//Let's assume that the Unicornlauncher constructor is also changed to  //Accept and use the usetinfoilshielding argument  return NewUnicornlauncher (ApiToken, usetinfoilshielding);};});

We have added protection to our application, and this time we need to create a configuration function module, and a unicornlauncherprovider must be injected in order to start normally:

function (Unicornlauncherprovider) {unicornlauncherprovider.usetinfoilshielding (true);}]);

Note that the unicorn is injected into the config function. Its injector is injected through the provider injector (provider injector) instead of the normal injector. (the next sentence does not know how to translate, on the original text) in the IT instantiates and wires (injects) all provider instances only.

During application startup, it instantiates and configures all providers (providers) before angular creates all of the services. We call this configuration phase the application life cycle. During this time, services are not available and are used because they have not been created yet!

After the configuration phase is over, it is no longer allowed to function with provider (not allowed, my understanding can no longer be modified), and then the process of creating the service begins. We call this phase the application life cycle run phase.

Constant Constants list Elements

We have already learned how to divide the life cycle of angular into configuration and operational phases. And you can configure your application with the Config function. Even if no service is empty, the config configuration function runs in the configuration phase, and you are not able to create a value object by using the value manifest element.

During the configuration phase we configured the name for Unicornlauncher. We can use it through a controller while the application is running. We want to define a constant that can do this:

Myapp.constant (' planetname ', ' greasy Giant ');

We can configure Unicornlauncherprovider for this:

function (Unicornlauncherprovider, PlanetName) {unicornlauncherprovider.usetinfoilshielding (true); Unicornlauncherprovider.stamptext (PlanetName);}]);

We can use the constant manifest element constant to create a valid constant, or we can use the value list element at run time to configure it, and we can use it in our controller and template:

 myapp.controller (' Democontroller ', ["ClientId", "PlanetName", function  Span style= "COLOR: #000000" > Democontroller (ClientId, planetname) { this . ClientId = clientId;  this . PlanetName = PlanetName;}]);  
<ng-app= "myApp"><ng-controller = "Democontroller as demo" >  <br>  Planet Name: {{demo.planetname}}</  body></html>

Objects of Special purpose

We have mentioned that we will also need to give our different services to create objects of special purpose. These objects as a plug-in to extend our framework, then such an object will need to implement some angular specified interface. These interfaces allow Controller,directive,filter and animation.

Let's take a look at using injector to create these special objects (except Controller objects). The factory factory manifest element is then used in the background to bind. Let's see how we can create a very simple component with the Plaetname constants we've just defined, using angular's instructions.

We already know that we can register an instruction by factory the factory list element, and we can use the same syntax for factory:

function myplanetdirectivefactory (planetname) {//  Directive definition objectreturn  {  ' E ',  scope: {},  function($scope, $element) {$element. Text (' Planet: ' + planetname); }}}]);

We can then use this component:

<ng-app= "myApp"><body><  my-planet></my-planet></body > </ HTML >

With the factory factory manifest element, you can also define the filter (filter) and animation (animation) of the Angularjs, but it's a bit special if you want to create a controller. You create a controller of a custom type, and you can then specify in its declaration the object type that it depends on in its constructor. This constructor is registered in the module. Let's take a look at one of our early examples:

function Democontroller (clientId) {this. clientId = clientId;}]);

In the application, every time we need to instantiate a democontroller (in our case, only once), it instantiates a Democontroller object through its constructor. So it's not like a service, it's a singleton pattern . The service can be invoked in its constructor, and our example calls the Dlientid service.

Summary

1. The injector (injector) uses the elements in the manifest to create two objects: The Service section special object.

2. In our list, there are five types of manifest elements: Value, Factory, Service, Provider, Constant.

3. Factory and Service list elements are the most common. The only difference between them is that the service manifest element is more suitable for the creation of objects of the custom type, while the factory manifest element can use JavaScript primitives and functions.

4. The provider manifest element is a very core list element type, and all other manifest element types are based on its syntax sugar.

5. Provider is the most complex type of manifest element. Unless you really need to build a reusable, globally generic code, you don't need it.

6. In the definition of all special objects, only the controller definition is configured by the factory manifest element.

Attribute/manifest Element type Factory Service Value Constant Provider
Whether there can be dependencies Yes Yes No No Yes
Support for using type injection No Yes Yes* Yes* No
object is valid in the configuration (config) phase No No No Yes yes**
Can create functions (function) Yes Yes Yes Yes Yes
You can create primitives Yes No Yes Yes Yes

* Represents the need for you to use the new operator to initialize directly

* * Delegates are not valid at Config configuration stage, but provider instances are valid (see the Unicornlauncherprovider example above)

AngularJS--Provider (Providers)

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.