AngularJS Factory vs Service vs Provider "Go"

Source: Internet
Author: User

English Original: Angularjs:factory vs Service vs Provider

When you Angular, it's natural to heap unnecessary logic in the controller and scope. Be sure to realize early that the controller layer should be thin, that is, most of the business logic and persistent data in the application should be in service. I see a couple of similar questions on Stack Overflow every day about how to save persistent data in a controller. This is not what the controller should do. For memory performance, the controller initializes only when needed, and is discarded once it is not needed. Therefore, each time you switch or refresh the page, Angular will empty the current controller. At the same time, the service can be used to permanently save the app's data, and the data can be used between different controllers.

Angular provides 3 ways to create and register our own service.

  1. Factory

  2. Service

  3. Provider

If you are "too long don't Look"

1) with   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)   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.

detailed explanation (for readers who are not "too long to see")

To accurately show Factory, The difference between service and Provider, here we build the same service in 3 different ways. This service uses the ITunes API and the promise that uses $q.

1) Factory

Factory is the most common way to create and configure services. There is nothing to add except a "Quick Tour". Just create an object, add properties to it, and return to this object. When you pass the factory into the controller, these properties of the object can be accessed through factory. A more detailed example is the following:

Creates an object first, and then returns the object, as follows.

Now if we pass "MyFactory" into the controller, any properties attached to "service" can be accessed.

Now let's add some "private" variables to the callback function. Of course, there is no direct access to these variables in the controller, but we will eventually set up setter and getter methods in the "service" to modify these "private" variables if necessary.

You may have noticed that we did not add the variable/function to the service. We simply create them for later use and modification.

  •  baseurl   is the root URL required by the itunes API

  •  _artist   is the artist we want to find

  • _finalurl   Is the final right-limiting URL, which is the entry we call itunes

  • Makeurl   is a function that creates and returns a friendly Itunesurl

Since our helper/private variables and functions are in the right place, let's add some attributes to the service object. No matter what we add to the service, we can use it in any controller that we pass into the ' myfactory '.

Let's create the Setartist and Getartist methods to simply return or set artist. Also create a method to invoke the itunes API using the URL we created. This method will return a promise that will be satisfied after getting the data from the itunes API. If you don't have much contact with angular promise, I highly recommend that you study it in depth.

  • setartist   accept a artist and allow you to set artist

  • getartist   returns artist

  • callitunes   first calls the Makeurl () method to build the URL used by the $http request. Then it will set the Promise object, let $http request our final URL, and then, because $http returns a promise, we can call after the request. Success or. Error. Finally we can use itunes data to parse our promise, or simply ' there is an error ' to reject it.

 

Now our factory is done. We can inject "myfactory" into any controller, and then we can invoke the methods we added to the service object (Setartist,getartist, and Callitunes).

In the controller above, we injected the ' myfactory ' service object. We then set the properties of the $scope object. The only tricky code above is handling promise. Since Callitunes returns a Promise object, once our promise is satisfied, we can call the. Then () method and set the $scope.data.artistdata. You will notice that our controller is very "thin". Because all of our logical and persistent data is stored in the service and not in the controller.

2) Service

When we create a service, the most important thing we know is that the service instantiates the object with the New keyword. This should make it possible for people familiar with JavaScript to understand what this piece of code does. But it may be a bit difficult for someone who has a limited JS background or is less familiar with the role of the new keyword. So let's revisit the basic JavaScript functionality to help us understand what the service is doing.

Let's define a function and then invoke it with the new keyword to see what it does when the interpreter encounters the New keyword to help us understand what happens when we instantiate a function using the new keyword. The end result should be the same as the service.

/tbody>

First, let's define a constructor. The

is a typical JavaScript-style construction method. Now, whenever we invoke the person function with the new keyword, we bind the ' this ' keyword to the newly created object.

Next, let's add a method to the prototype object for person, which is available for all instances of the person ' class '.

Now, because we have added a Sayname method to prototype, all the person instances can call this method and output the name value of the corresponding instance.

Now that we have a constructor for the person and defined a Sayname method on its prototype, let's create an instance of the person and invoke the Sayname method.

Next, we'll create the person constructor, add a method to its prototype, create a person instance, and call the code for the Sayname method in one piece, as follows:

Now, let's look at what happens when we use the New keyword in JavaScript. The first thing you should notice is that when we use the New keyword in the example, we can invoke the method through ' Tyler ' (Sayname), which looks like Tyler is an object-that's because it's actually an object. So the first thing we know is that our person constructor returns an object. Second, we know that because our Sayname method is defined on the prototype of the person, not directly on the instance of person, the object returned by the person function (Tyler) must be because the Sayname method was not found. And then went to prototype to find the Sayname method. In more popular terms, when we call Tyler.sayname (), the JS interpreter says, "Well, I'll go first to the ' Tyler ' object we just created, find the Sayname method, and then call it." Wait a minute, I didn't find the Sayname method on it--I only saw the name and age, so let me go to prototype for a look. Yes, it's on the prototype, so let me call it. "

The following code demonstrates what to do after using the new key in JavaScript. It is a basic code example for this paragraph of the above text. I've written the code in the comments about the entire process from the JS interpreter's point of view.

Now that we understand how the New keyword works in JavaScript, creating a service in angular should also be easy to understand.

The most important thing to understand when creating a service is that we use the New keyword to instantiate the service object. In combination with what we have learned from the above examples, you should have realized that you can add properties and methods directly to this, and then when you create a service object, this is returned as a return value. Let's take a look at this way of working.

We don't need to create an object as in the previous factory example, and then return to this object. Because we use the New keyword to invoke, the interpreter creates an object and associates it with its prototype object, and then returns the object without us having to do the work.

First, let's create our private helper functions. It should look very similar to the work we did in factory. Since I have explained the meaning of each line of code in the factory example, I will not explain it here more, if you have doubts, please relive the example of factory.

Next, we will add a method that can be accessed from the controller to the ' this '.

Now, as with factory, all controllers that pass MyService as parameters can access the setartist, Getartist, and Callitunes methods. The following is the controller that passed in the MyService (basically the same as the factory controller).

As I mentioned earlier, once you understand the role of the new keyword, you'll know that services and factories are almost the same in angular.

3) Provider

The most important thing to remember about provider is that they are the only services that you can pass to the App App. Config section. This is important if you need to change some parts of your service object before it can be available anywhere outside of your application. Although services/factories are similar, there are some differences and we will discuss them.

First, we build our provider in a similar way to our service and factory. The following variables are our ' private ' and accessibility features.

* Similarly, if any part of the above code is bothering you, take a look at the Factory section, where I explained in more detail the role of the Code.

It is important to note that only these variables and functions can be accessed in our App. config function. It was once confusing to me, so you'd better know the difference. You can think of provider as a two-part composition. The first part of the variables and functions can be accessed in the App. config function, so you can modify them as they are accessed elsewhere (as shown above). The variables and functions in the second section (shown below) can be accessed in any controller that has passed into the ' myProvider '.

When you create a service using provider, the only properties and methods that can be accessed in your controller are the content returned through the $get () function. The following code writes the $get method to ' this ' (which will eventually be returned by the function). Now, $get function returns all the methods and properties that we want to access in the controller. The following is a code example:

Now, the complete code for provider is as follows:

Now, like our factory and service, Setartist, Getartist, and callitunes can be accessed from any controller that has passed in MyProvider. The following is the MyProvider controller (almost the same as the controller in our Factory/service).

As mentioned earlier, creating a service with provider is unique in that you can modify it in the App. config function before the provider object is passed to other parts of the application. Let's take a look at a corresponding example.

Now you can see how ' thingfromconfig ' is an empty string in our provider, and when it appears in the DOM it will be ' this sentence is set ... '.

Thank you for reading, I hope this helps you to discern the difference between factory, Service, and provider in angular.

* To see the full code example, look at the code in the run and be free to fork my repo:https://github.com/tylermcginnis33/angularservice

AngularJS Factory vs Service vs Provider "Go"

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.