Follow me learn angularjs:service, Factory, provider Dependency injection use and difference

Source: Internet
Author: User

Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka

This tutorial uses the ANGULARJS version: 1.5.3

AngularJs github:https://github.com/angular/angular.js/

angularjs:https://angularjs.org/

As anyone with spring knows, the core idea of spring is Di (dependency injection,Dependency injection) and IOC (control reversal invension of controller), Angularjs service is actually used here di idea, then what is called di? refers to the object is passively accept the dependency class rather than take the initiative to find, in other words, the object is not from the container to find it depends on the class, Instead, it actively injects the class it relies on when the container instantiates the object. My personal understanding is that when you instantiate a class, it automatically instantiates the other instances it uses. So this is called dependency injection. In angular, services is created as a singleton object when needed, and is cleared only at the end of the application lifecycle (close the browser). and controllers will be destroyed when it is not needed.

There are three types of angualrjs that can be injected, service, factory, provider, these three styles are not the same, and the usage is different. Among them, the service is only instantiated once, in fact, is the idea of singleton mode. No matter where we inject our service, we will always use the same instance. So many operations in the controller layer can be put into the serivce layer. ANGULARJS provides many internal services such as: $http, $route, $window, $location, etc. Each service is responsible for, for example, a specific task, $http is used to create Ajax calls to obtain the server's data. $route used to define routing information, and so on. The built-in service always prefixes the $ sign.

Among them, the relationship between the three can be seen as:


First, service use detailed

(1) Definition

A learning service usage is as follows:

This is generally used to manipulate data and define functions directly.

App.service (' MyService ', function () {    var privatevalue = "I am Private";    This.variable = "This was public";    This.getprivate = function () {return privatevalue;};});

(2) Three ways to add a service using DI in Angularjs
Mode 1 (inline annotations, recommended):

App.controller (' Mycontroller ', [' $scope ', ' datefilter ', function ($scope, datefilter) {}]);
Mode 2 ($inject Note):
var mycontroller = function ($scope, datefilter) {}mycontroller. $inject = [' $scope ', ' datefilter ']; Somemodule.controller (' Mycontroller ', mycontroller);
Mode 3 (implicit annotation, deprecated):
App.controller (' Mycontroller ', function ($scope, datefilter) {});
the reasons for using Mode 1 are:
The notation is simpler and clearer than Method 2.
More reliable than Method 3 (since JavaScript can be compressed, Angularjs is also found by parsing the service name, so the JavaScript compression angularjs will not be able to find the specified service, but the string will not be compressed. Therefore, specifying the name of the service as a string alone avoids this problem)
note points for use mode 1 or Mode 2:
For the 2nd reason above, ANGULARJS maps the name of the service in the array to the service in the method body by $injector one by one when compiling the HTML. This mapping relationship must adhere to the conventions by Angularjs:
The number of service names in the array must be the same as the number of service names in the method body
The order of the service in the array must match the order of Serivce in the method body

(3) When it is appropriate to use the service () method
The service () method is well-suited for use in more functional control service
Note: You cannot use the service () method when you need to configure the service using. config ()

(4) Service Usage Example

A complete example:

<! DOCTYPE html>The effect is as follows:

In addition, from here you can see that two controllers inject the same service, but eventually only instantiated once!

Note: Services defined by Seivce cannot be used in. config! Only provider can be defined.
second, factory use detailedFactory typically creates an object, then adds methods and data to the object, and finally returns some objects. Then inject it into the controller layer.
Usage examples:
<! DOCTYPE html>Effect:
From below you can see that only one instance was instantiated, two controllers injected with the same factory, but eventually only instantiated once!
Remember to return an object, otherwise the following error will be reported:

Services in Angularjs:
third, provider use detailed$provide Service is responsible for telling angular how to create something new that can be injected: the service. Services are defined by what is called a vendor, and you can use $provide to create a vendor. You need to use the provider () method in $provide to define a vendor, and you can get $provide service by requiring $provide to be injected into an application's config function. The use method is to return a $get function, noting that only provider can be injected during the Config phase. Other usages are the same as service. Here is an example.
<! DOCTYPE html>Effect:
You can see that only one instantiation has been made from the following: Let's do a time test of provider instantiation:
<! DOCTYPE html>after the page is refreshed, we find that even if we do not inject this providrer, it is instantiated, and Service/factory is initialized the first time it is injected. And that's one of the reasons why it can be injected into config! When to use the provider () method

(1) We need to use the provider () when we want to configure the service before the app starts. For example, we need to configure services in different deployment environments (development, presentation, production) using a different backend (2) When you can use the
When we are going to publish open source provider () is also preferred to create a service, so that you can configure services using configuration instead of hard-coding the configuration data into the code.


Four, Service, Factory, provider three difference
1 using Factory is to create an object, add a property to it, and then return the object. After you pass the service into the controller, the properties of this object in the controller can be used by factory.
2) The Service is instantiated with the "new" keyword. Therefore, you should add a property to "this" and then the service returns "this". After you pass the service into the controller, the properties on the "This" in the controller can be used by the service.
3) Providers is the only service that you can pass into the. config () function. When you want to make a module-wide configuration before the service object is enabled, you should use provider.
4) Factory/service is instantiated as the first injection, and provider is not, it is instantiated before config.Three different ways to do the same function:
<! DOCTYPE html>

Look at the output of the console, you can know that it is only instantiated once:

Reference article: Http://www.cnblogs.com/wushangjue/p/4533953.html?utm_source=tuicool&utm_medium=referral
Http://www.oschina.net/translate/angularjs-factory-vs-service-vs-provider
http://my.oschina.net/tanweijie/blog/295067
Http://www.360doc.com/content/15/1010/18/28162318_504719466.shtml

Follow me learn angularjs:service, Factory, provider Dependency injection use and difference

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.