The difference between Serivce,factory,provider in Angularjs

Source: Internet
Author: User
Tags log log

First, service guidance

when I first started learning angular, the components that were often misunderstood and asked by beginners were the differences between service (), factory (), and provide (). This is where we'll start the twenty-five days of Angular calendar.

Second, service

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.

This is why using controllers to pass data in applications is unreliable, especially when using routing. Services is designed to be the glue between controllers, the minions of data, the slaves of functionality, the Worker-bee S of our application (that is, services play a key role in the application of controllers, methods, data)


Now we start to see how to Create the service. We will see the following two parameters for each method:

    • name-the name of the service we want to define

    • Function-service method

They all create the same underlying object type. after instantiation, they all create a service that has no functional differences.

1, Factory ()

The simplest way to create a service inside angular is to use the factory () method.

factory () lets us define a service by returning an object that contains the service method and data. Within the service method we can inject services such as $http and   $q.

Angular.module (' myapp.services '). Factory (' User ',  function ($http)  { // injectables go  here  var backendUrl =  "http://localhost:3000";   var service  = {    // our factory definition    user:  {},    setname: function (NewName)  {        service.user[' name '] = newname;     },     Setemail: function (newemail)  {      service.user[' email '] =  Newemail;    },    save: function ()  {       return  $http. Post (backendurl +  '/users ', {         user: service.user      });     }   };  return Service;}); 

Use the factory () method inside the application

It's easy to use factory in the app, and it's easy to inject when you need it.

Angular.module (' myApp '). Controller (' Mainctrl ', function ($scope, User) {$scope. Saveuser = User.save;});

When to use the factory () method

In the service, factory () is a great choice when we only need a collection of methods and data and do not need to deal with complex logic.

Note: You cannot use the factory () method when configuring the service with. config ()

2. Service ()

Service () lets us create a service by constructors, and we can define the service using prototype mode instead of the original JavaScript object.

As with the factory () method, we can also see the injection of the service in the definition of the function.

Angular.module (' myapp.services '). Service (' User ', function ($http) {//injectables go here var = this;//Save Refere  nCE this.user = {};  This.backendurl = "http://localhost:3000";  This.setname = function (newName) {self.user[' name '] = NewName;  } This.setemail = function (newemail) {self.user[' email '] = Newemail; } This.save = function () {return $http. Post (Self.backendurl + '/users ', {User:self.user})});

Here, as with the factory () method, the service () method holds the object created by the constructor.

    • Use the service () method inside the app

Angular.module (' myApp '). Controller (' Mainctrl ', function ($scope, User) {$scope. Saveuser = User.save;});

    • When is it 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 ()

3, provider ()

Provider () is the lowest level of service creation, and the only way to configure service creation using the. config () method

Unlike the method mentioned above, we do a dependency injection in the definition of this $get () method.

Angular.module (' Myapp.services '). Provider (' User ',  function ()  {  this.backendurl =   "http://localhost:3000";   this.setbackendurl = function (Newurl)  {     if  (URL)  this.backendurl = newurl;  }  this. $get  =  function ($http)  { // injectables go here    var self  = this;    var service = {       User: {},      setname: function (NewName)  {         service.user[' name '] = newname;      },       setemail: function (Newemail)  {         service.user[' Email '] = newemail;      },       save:&nBsp;function ()  {        return  $http. Post (Self.backendurl  +  '/users ', {          user:  service.user        })       }     };    return service;  }});

    • Use the provider () method inside the application

In order to configure the service, we can inject the provider into the. config () method

Angular.module (' myApp '). config (function (userprovider) {Userprovider.setbackendurl ("Http://myApiBackend.com/api") );})

So that we can use the service in the app like any other way.

Angular.module (' myApp '). Controller (' Mainctrl ', function ($scope, User) {$scope. Saveuser = User.save;});

    • 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 to use different backend processing in different deployment environments (development, demo, production) .

    2. 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.

Understanding Angular ServicesWhat is angular Service

A Angular service is a singleton object or method that performs a specific task for a Web application. Note: If a component is reused for the functionality of the content rendering, then the service is functional reuse for the component.

Angular has some built-in services (for example: $http), or you can create your own services. Built-in services typically start with "$" (similar to jquery).

Using the angular service

Angular uses "constructor" (constructor) for trust injection. Trust is passed to the factory or constructor method of the component. Because JavaScript is a dynamic type of language, angular's trust injection subsystem cannot use static types to identify the trust of the service. Therefore, a component must explicitly define its trust by using a "comment" injection method. For example, use the $inject property:

var mycontroller = function ($location) {...}; Mycontroller. $inject = [' $location '];mymodule.controller (' Mycontroller ', mycontroller);

Alternatively, provide an inline injection "comment":

var myservice = function ($http) {...}; Mymodule.factory (' MyService ', [' $http ', MyService]);

Reference:

    • $location

Define a service

app developers define their own services by registering "name" and "Service factory" in the angular module.

The purpose of the factory method of the service is to generate singleton objects (or method function). The generated object or method can be injected into any component by assigning trust to the service.

Angular factory methods use a passive execution strategy, which means that only one execution is performed for each service when a dependency needs to be processed. All of this is dependent on the service to obtain an instance generated by the service factory method.

Management Services Trust

angular allows services to declare other services as trust needs and to construct instances of them.

To declare dependencies, you can specify them in the parameters of the factory method, and then use the $inject property, string array, or array comment to inject annotations to indicate this method.

Using array annotations:

function Mymodulecfgfn ($provide) {$provide. Factory (' MyService ', [' dep1 ', ' Dep2 ', function (DEP1, DEP2) {}]);}

Use the $inject property:

The following is an example of two services, one of which relies on another, and both services rely on other services provided by the angular framework:

Attention:

    • The Batchlog service relies on built-in $timeout and $log services, and allows messages to be exported to console.log log files.

    • Routetemplatemonitor services rely on built-in $route services like our custom batchlog services.

    • Our two services use factory methods to identify and group comments to inject annotations to declare their dependencies. It is important to note that the order of the strings in the array is consistent with the list of parameters in the factory method. Unless the dependency is inferred from the parameter list of the method, the array with IDs and the order in which they are injected determines where the services are injected.


The difference between Serivce,factory,provider in Angularjs

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.