Three ways to create a service in angular factory, service, provider

Source: Internet
Author: User
Tags constructor http request
1. English version angularjs:factory vs Service vs ProviderBy Tyler on the May 4, with the 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 are 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 F Irst 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 ' th

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.