[Reprint] I see the best explanation angularjs in factory and service and provide different

Source: Internet
Author: User

Angularjs:factory vs Service vs Provider
    • by Tyler
    • On May 4, 2014
    • With Comments
    • In Technical

When you first get started with Angular, you'll naturally find yourself flooding your controllers and scopes with unnecess ary logic. It's important to realize early on this your controller should be very thin; Meaning, most of the business logic and persistent data in your application should being taken care of or stored in a service . I see a few questions a day on the Stack Overflow regarding someone trying to has persistent data in his or her controller. That's just not the purpose of a controller. For memory purposes, controllers is instantiated only when they is needed and discarded when they is not. Because of this, every time switch a route or reload a page, Angular cleans up the current controller. Services however provide a means for keeping data around for the lifetime of a application while they also can be used AC Ross different controllers in a consistent manner.

Angular provides us with three ways to create and register our own service.

1) Factory

2) Service

3) Provider

Tl;dr

1) When your ' re using a Factory you create an object, add properties to it, then return this same object. When you pass this service to your controller, those properties on the object would now is available in that controller T Hrough your factory.

2) When you ' re using Service, it's instantiated with the ' new ' keyword. Because of that, you'll add properties to ' this ' and the service'll return ' this '. When you pass the service to your controller, those properties on ' this ' 'll now is available on that controller Throug H your service.

3) Providers is the only service can pass into your. config () function. Use a provider if you want to provide module-wide the configuration for your service object before making it available.

NON TL;DR

In order to extensively show the difference between a Factory, Service, and Provider, we ' re going to build the same Servic E in three separate ways. The services is going to utilize the ITunes API as well as promises with $q.

1) Factory

Factories is the most popular-to create and configure a service. There ' s really not much more than what the TL;DR said. You just create a object, add properties to it, and then return this same object. Then if you pass the factory to your controller, those properties on the object would now is available in that controll Er through your factory. A More extensive example is below.

First we create an object and then return this object like so.

Now whatever the properties we attach to ' service ' would be available to us when we pass ' myfactory ' into our controller.

Now let's add some ' private ' variables to our callback function. These won ' is directly accessible from the controller, but we'll eventually set up some getter/setter methods on ' servi Ce ' to is able to alter these ' private ' variables when needed.

Here you'll notice we ' re not attaching those variables/function to ' service '. We ' re simply creating them in order to either with or modify them later.

      • BASEURL is the base URL, the ITunes API requires
      • _artist is the artist we wish to lookup
      • _finalurl is the final and fully built URLs to which we'll make the call to ITunes
      • Makeurl is a function, that would create and return our ITunes friendly URL.

Now, our helper/private variables and function is in place, let's add some properties to the ' Service ' object. Whatever we put on ' service ' we'll be able to directly use in whichever controller we pass ' myfactory ' into.

We is going to create setartist and Getartist methods that simply return or set the artist. We is also going to create a method that would call the ITunes API with our created URL. This method was going to return a promise that would fulfill once the data have come back from the ITunes API. If you haven ' t had much experience using promises in Angular, I highly recommend doing a deep dive on them.

    • Setartist accepts an artist and allows your to set the artist
    • Getartist returns the artist
    • Callitunes first calls Makeurl () in order to build the URL of we ' ll use with our $http request. Then it sets-a Promise object, makes an $http request with our final URL, then because $http returns a promise, we are able to call. Success or. Error after we request. We then resolve our promise with the iTunes data, or we reject it with a message saying ' There is an error '.

Now we factory are complete. We is now able to inject ' myfactory ' into any controller and we'll then is able to call our methods so we attached to O Ur service object (setartist, Getartist, and Callitunes).

The controller above we ' re injecting in the ' myfactory ' service. We then set the properties on our $scope object, which is coming from the data from ' myfactory '. The only tricky code above are if you've never dealt with promises before. Because Callitunes is returning a promise, we be able to use the. Then () method and only set $scope. Data.artistdata Once Our promise are fulfilled with the iTunes data. You'll notice our controllers is very ' thin '. All of our logic and persistent data are located in our service, not with our controller.

2) Service

Perhaps the biggest thing to know when dealing with creating a Service is so that it's instantiated with the ' new ' keyw Ord. For your JavaScript gurus this should give your a big hint into the nature of the code. For those of a limited background in JavaScript or for those who aren ' t too familiar with what the ' new ' keyword Actually does, let's review some JavaScript fundamentals that'll eventually help us in understanding the nature of a Se Rvice.

To really see the changes so occur when you invoke a function with the ' new ' keyword, let's create a function and invoke It with the ' new ' keyword and then let's show what the interpreter does when it sees the ' new ' keyword. The end results'll both be the same.

First let's create our Constructor.

This is a typical JavaScript constructor function. Now whenever we invoke the person function using the ' new ' keyword, ' this ' 'll be bound to the newly created object.

Now let's add a method onto our person's prototype so it'll be available on every instance of our person ' class '.

Now, because we put the Sayname function on the prototype, every instance of person would be able to call the Sayname funct Ion in order alert that instance ' s name.

Now the We have the constructor function and our Sayname function on their prototype, let's actually create an Insta NCE of person then call the Sayname function.

So all together the code for creating a person constructor, adding a function to it's prototype, creating a person Instanc E, and then calling the function in its prototype looks like this.

Now let's look at what's actually is happening if you use the ' new ' keyword in JavaScript. First thing you should notice was that after using the ' new ' in our example, we ' re able to call a method (Sayname) on ' Tyler ' J UST as if it were an object–that ' s because it is. So first, we know, we are constructor is returning a object, whether we can see this in the code or not. Second, we know that because our Sayname function are located on the prototype and not directly on the person instance, the object, the person function is returning must are delegating to their prototype on failed lookups. In + simple terms, when we call Tyler.sayname () The interpreter says "OK, I ' m going to look on the ' Tyler ' object we Ju St created, locate the Sayname function, then call it. Wait a minute, I don ' t see it here–all I See was name and age, let me check the prototype. Yup, looks like it's on the prototype, let me call it. "

Below is code for how can think about what the ' new ' keyword are actually doing in JavaScript. It ' s basically a code example of the above paragraph. I ' ve put the ' interpreter view ' or the ' the ' interpreter sees the code inside of notes.

Now have this knowledge of the ' new ' keyword really does in JavaScript, creating a Service in Angular should is EAS Ier to understand now.

The biggest thing to understand when creating a Service was knowing that Services was instantiated with the ' new ' keyword. Combining that knowledge with our examples above, you should now recognize so you'll be attaching your properties and me Thods directly to ' this ' which'll then is returned from the Service itself. Let's take a look at the in action.

Unlike what we originally do with the Factory example, we don ' t need to create a object then return this object because, Like mentioned many times before, we used the ' new ' keyword so the interpreter would create that object with it delegate To it's prototype, then return it for us without us have to do the work.

First things first, let's create our ' private ' and helper function. This should look very familiar since we do the exact same thing with our factory. I won ' t explain what's each line does here because I did so in the factory example, if you ' re confused, re-read the factor y example.

Now, we'll attach all your methods that'll be available in our controllers to ' this '.

Now just like in our factory, Setartist, Getartist, and Callitunes would be available in whichever controller we pass Myser Vice into. Here's the MyService controller (which is almost exactly, the same as our factory controller).

Like I mentioned before, once you really understand what ' new ' does, Services is almost identical to factories in Angular .

3) Provider

The biggest thing to remember about Providers are that they ' re the only service so can pass into the the app. config Porti On your application. This is the huge importance if you ' re needing to alter some portion of your service object before it ' s available everywhere else in your application. Although very similar to services/factories, there is a few differences which we ' ll discuss.

First we set up our Provider in a similar we do with our Service and Factory. The variables below is our ' private ' and helper function.

*again if any portion of the above code are confusing, check out the Factory sections where I explain what it all does it gr Eater details.

You can think of Providers as have three sections. The first section was the ' private ' variables/functions that would be modified/set later (shown above). The second section was the variables/functions that would be available in your app. config function and is therefore availab Le to alter before they ' re available anywhere else (also shown above). It's important to note, those variables need to being attached to the ' this ' keyword. In we example, only ' Thingfromconfig ' is available to alter in the App. CONFIG. The third section (shown below) was all the variables/functions that would be available in your controller when you pass in The ' MyProvider ' service into that specific controller.

When creating a service with Provider, the only properties/methods that'll be is available in your controller is those pro Perties/methods which is returned from the $get () function. The code below puts $get on ' this ' (which we know would eventually be returned from that function). Now, this $get function returns all the methods/properties we want to being available in the controller. Here ' s a code example.

Now the full Provider code looks like this

Now just like with our factory and Service, Setartist, Getartist, and Callitunes would be available in whichever controller W E pass myProvider into. Here's the MyProvider controller (which is almost exactly, the same as our Factory/service controller).

As mentioned before, the whole point of creating a service with Provider are to being able to alter some variables through the App. Config function before the final object is passed to the rest of the application. Let's see a example of that.

Now you can see how ' thingfromconfig ' was as empty string in we provider, but if that shows up in the DOM, it'll be ' T He sentence was set ... '.

Thank you-reading and I hoped this helped I-be able to discern the difference between Factory, Service, and Provi Der in Angular.

*to See the full code example and see the Code in action, feel free to fork my repo at https://github.com/tylermcginnis33/ Angularservices

[Reprint] I see the best explanation angularjs in factory and service and provide different

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.