ANGULARJS Application Development Thinking 3: Dependency Injection

Source: Internet
Author: User

Can't find the API?

ANGULARJS provides some functionality for encapsulation, but when you try to access these features through the global object angular, you find that it is very different from the libraries you have encountered before.

    • $http

For example, in jquery, we know that its API is exposed by a global object: $ $.ajax () when you need to make an Ajax call. Such APIs are in line with thinking expectations.

Angularjs also exposes a global object: angular, which also encapsulates an AJAX call to provide a $http object, but, when you try to follow the old experience to access angular. $http, it's not what happened!

Look closely at $http's documentation and find a little clue where you can get the $http.

    • Dependency Injection/di

In fact, ANGULARJS organizes all of the functional components in a dependency injection way:

In a dependency injection mode, all components must pass through the container to access each other, which results in the ANGULARJS that you must pass an intermediary to obtain an instance object for a component:

    1. var injector = angular. Injector([' ng ']);
    2. Injector. Invoke(function($http) {
    3. //do sth. With $http
    4. });

This intermediary, which is the container in the injection pattern, is called the injector in Angularjs.

In →_→ 's example, we can see that we've got the $http object, which is actually a function.

Demo Example: http://www.hubwiz.com/course/54f3ba65e564e50cfccbad4b/

Injector/injector

Injector is the key of ANGULARJS framework implementation and application development, which is the implementation of a DI/IOC container.

Angularjs functions are divided into different types of components, each of which has a collectively-provider/provider, which lists several common built-in services for ANGULARJS:

ANGULARJS components cannot be called directly to each other, and one component must pass the injector to invoke another component. The benefit is that the components are decoupled from one another, and the entire life cycle of the object is managed by the injector.

The injector implements two important functions:

    1. Centralized storage of all provider recipes

The recipe is actually: Name + class constructor. When Angularjs starts, these provider are first registered with their recipes in the injector. For example, the HTTP request service component is encapsulated within the $httpprovider class, which is registered in the injector by the name "$http".

    1. Provide instances of functional components on demand

Other components, such as a user's controller, if you need to use the HTTP function, use the name "$http" to the injector to request, you can obtain an HTTP service instance.

Try modifying the →_→ code to see what the next $compile service is all about.

Demo Example: http://www.hubwiz.com/course/54f3ba65e564e50cfccbad4b/

Registering Service Components

From Injector's point of view, a component is a function provider and is therefore called the supplier/provider. In Angularjs, provider is encapsulated in the form of a JavaScript class (constructor).

Service names are typically identified by a string, such as "$http" represents the HTTP invocation service, "$rootScope" represents the root scope object, "$compile" represents the build service ...

The provider class requires a $get function (class factory), and injector can obtain an instance of the serviced component by invoking the function.

The combination of name and class function information is called a recipe. A centralized recipe library is maintained in injector to create different components on demand. This recipe library, in fact, is a hash object, key is the service name, value is the class definition.

In →_→ 's example, we define a simple service class, where an instance of the service class is a string: "hello,world!". We use "Ezhello" as its service name to register in the injector and display the instance through the injector.

Demo Example: http://www.hubwiz.com/course/54f3ba65e564e50cfccbad4b/

Get the Injector Object

To use the functionality of ANGULARJS, you must first obtain an injector. There are two ways to get an injector.

    • Create a new injector

You can use Angular.injector () to create a new injector:

    1. Angular. Injector(modules, [strictdi]);
    • Get an injector that has already been created

If the ANGULARJS framework is already started, you can use the injector () method of the DOM object to get the injector already created:

    1. var element = angular. Element(dom_element);
    2. var injector = element. Injector();
Invoking the API via the injector

The injector has two methods to make API calls: Invoke () and get ().

    • Invoke ()

Using the Invoke () method of the injector, you can invoke a user-defined function body directly and inject the dependent service object through the function parameters, which is the usage of ANGULARJS recommendations and conventions:

    1. Angular. Injector([' ng '])
    2. . Invoke(function($http) {
    3. //do sth. With $http
    4. });
    • Get ()

You can also use the Get () method of the injector to obtain a service instance of the specified name:

    1. var my$http = angular. Injector([' ng ']). Get(' $http ');
    2. Do sth. With My$http

→_→ example this time using the Get () method to get a service instance directly, feel it!

Demo Example: http://www.hubwiz.com/course/54f3ba65e564e50cfccbad4b/

The way and principle of injection

There are two ways to tell the injector that a service object needs to be injected: parameter name injection and dependency array injection.

    • Parameter name injection

Angularjs when executing the Invoke () function, converts the function definition to be injected into a string and examines its parameter table through a regular expression to discover and inject the service object on which it depends:

    1. MyFunc This function is dependent on the "$http" service through the parameter table
    2. var myfunc = function($http) {
    3. //do sth. With $http
    4. };
    5. Injector. Invoke(myfunc); The definition of MyFunc will be converted to a string for parameter name checking

The problem with this is that when we compress the JavaScript code, $http may be changed to another name, which results in an injection failure.

    • Dependency array Injection

Angularjs uses the method of dependency array to solve the problem of code compression confusion. The incoming invoke () is an array, the last item of the array is the actual function to execute, and the other item indicates the name of the service that needs to be injected into the function. The injector will inject the dependent object into the function in sequence, in the order of the array.

In this way, the name of the parameter table of the function to be injected does not matter:

    1. MyFunc relies on "$http" and "$compile" services
    2. var myfunc = ["$http","$compile",function(p1,p2) {
    3. //do sth. with P1 ($http), p2 ($compile)
    4. }];
    5. Injector. Invoke(myfunc);

→_→ example of the use of an array-dependent method to inject the Ezhello service instance, you can change the parameter name to see if there is any impact results?

Reference: http://www.hubwiz.com/course/54f3ba65e564e50cfccbad4b/

ANGULARJS Application Development Thinking 3: Dependency Injection

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.