banner



How To Get New Instance Of Service Angular 1.6

I was giving a workshop earlier this week, and as the workshop came to a close and people were leaving, an attendee asked if I could explain the difference betwixt a factory and service. Anybody seemed to pause and terminate packing upwardly their things, and saturday back downward to heed to the additional 15 minute showdown on the API differences. So in my words this the reply to .factory() and .service().

And so, you may be thinking again we know the answer already to this, however the masses of answers online merely show how you lot can do the aforementioned thing with .mill() and .service(), without explaining what you can do with the APIs. They also paste in the aforementioned code snippet from the Angular source saying that a Mill is just a Service and Service is merely a Manufactory only there'south 1 line of code different and so on, this is meaningless to teaching the developer how to actually use the APIs - so permit's give them a little perspective that answer questions I've been asked online and in person.

Table of contents

  • Service
    • So, what is a service?
    • When should yous utilise it?
  • Factory
    • Manufactory: Object Literals
    • Manufactory: Closures
    • Factory: Creating Constructors/instances
  • Conclusion

Service

Allow's outset with .service(). First, a quick example of a Service with a bones $http.get() implementation:

                          function              InboxService              (              $http              )              {              this              .              getEmails              =              office              getEmails              ()              {              return              $http              .              become              (              '              /emails              '              );              };              }              athwart              .              module              (              '              app              '              )              .              service              (              '              InboxService              '              ,              InboxService              );                      

We tin then inject this into a Controller and fetch some emails:

                          function              InboxController              (              InboxService              )              {              InboxService              .              getEmails              ()              .              then              (              office              (              response              )              {              // use response              });              }              angular              .              module              (              '              app              '              )              .              controller              (              '              InboxController              '              ,              InboxController              );                      

Delightful. We all know this, don't nosotros.

So, what is a service?

A Service is but a function for the business layer of the awarding. It acts as a constructor office and is invoked once at runtime with new, much like you would with plainly JavaScript (Angular is just calling a new instance under the hood for us).

Recollect about it being just a constructor method, yous tin add public methods to it and that's pretty much information technology. Information technology'south a simple API, don't overthink it.

When should you use it?

Use a .service() when you lot desire to merely create things that act as public APIs, such as the getEmails method we defined above. Use information technology for things yous would use a constructor for. Unfortunately if yous don't similar using constructors in JavaScript, there isn't much flexibility if you desire to just apply a simple API pattern. However, you can achieve identical results by using the .factory() method, but the .factory() method is much different, permit's have a expect.

Factory

Adjacent, the confusing .manufactory() method. A factory is non just "another way" for doing services, anyone that tells you that is wrong. It can however, give you the same capabilities of a .service(), but is much more powerful and flexible.

Angular Directives In-Depth eBook Cover

Free eBook

Directives, simple right? Wrong! On the outside they look unproblematic, but even skilled Athwart devs oasis't grasped every concept in this eBook.

A factory is not just a "way" of returning something, a factory is in fact a design pattern. Factories create Objects, that's it. Now ask yourself: what type of Object do I want? With .factory(), we tin can create diverse Objects, such every bit new Class instances (with .prototype or ES2015 Classes), return Object literals, return functions and closures, or even just return a merely String. You tin can create whatever y'all like, that'southward the rule.

Allow's take a await at some examples that usually go shown with these "factory versus service" manufactures:

                          // Service              office              InboxService              (              $http              )              {              this              .              getEmails              =              function              getEmails              ()              {              return              $http              .              get              (              '              /emails              '              );              };              }              angular              .              module              (              '              app              '              )              .              service              (              '              InboxService              '              ,              InboxService              );              // Manufacturing plant              office              InboxService              (              $http              )              {              return              {              getEmails              :              function              ()              {              return              $http              .              get              (              '              /emails              '              );              }              };              }              angular              .              module              (              '              app              '              )              .              factory              (              '              InboxService              '              ,              InboxService              );                      

Yes yes, we tin can inject both versions into a Controller and telephone call them in identical means by using InboxService.getEmails();. This is usually where all explanations end, but come on, you don't demand to terminate at that place. A Factory is flexible, we can return anything. A mill creates things, or at least can practise. With the above example it doesn't actually create annihilation, it just returns an Object literal. Let's add a further example beneath then walkthrough the other things we can exercise with the .factory() method:

Manufactory: Object Literals

As above, nosotros can define some functions on an Object and return them. This is just basic module pattern implementation:

                          part              InboxService              (              $http              )              {              render              {              getEmails              :              function              ()              {              return              $http              .              get              (              '              /emails              '              );              }              };              }              athwart              .              module              (              '              app              '              )              .              factory              (              '              InboxService              '              ,              InboxService              );                      

We can also utilise the revealing module pattern as a variant:

                          function              InboxService              (              $http              )              {              function              getEmails              ()              {              return              $http              .              become              (              '              /emails              '              );              }              return              {              getEmails              :              getEmails              };              }              angular              .              module              (              '              app              '              )              .              manufacturing plant              (              '              InboxService              '              ,              InboxService              );                      

I much prefer this syntax as it allows for nicer lawmaking indentation and better comments above the function definitions.

Factory: Closures

We can render a closure from a .manufacturing plant() as well, which we may want to do to purely betrayal a single function call.

                          function              InboxService              (              $http              )              {              render              function              ()              {              return              $http              .              get              (              '              /emails              '              );              };              }              angular              .              module              (              '              app              '              )              .              manufacturing plant              (              '              InboxService              '              ,              InboxService              );                      

We would utilize information technology like then within the Controller:

                          function              InboxController              (              InboxService              )              {              InboxService              ().              then              (              function              (              response              )              {              // use response              });              }              athwart              .              module              (              '              app              '              )              .              controller              (              '              InboxController              '              ,              InboxController              );                      

Using the $http instance here isn't a dandy example, however demonstrates what we can render from a .manufacturing plant() call. As we're returning a closure, we can too return other things within the closure that make using a closure the sensible options:

                          part              InboxService              (              $http              )              {              render              function              (              collection              )              {              return              office              (              something              )              {              drove              .              forEach              (              function              (              particular              )              {              // manipulate each collection `item` and also              // use the `something` variable              });              };              };              }              angular              .              module              (              '              app              '              )              .              factory              (              '              InboxService              '              ,              InboxService              );                      

Some case usage:

                          function              InboxController              (              InboxService              )              {              var              myService              =              InboxService              ([{...},{...}]);              var              callTheClosure              =              myService              (              '              foo              '              );              }              angular              .              module              (              '              app              '              )              .              controller              (              '              InboxController              '              ,              InboxController              );                      

The above Controller example passes in a drove, then return a closure to pass further information into. There are use cases for this you've likely come beyond.

Factory: Creating Constructors/instances

We've learned that .service() is the constructor role, only is just invoked in one case, even so that doesn't hateful nosotros cannot create constructor Objects elsewhere that we can telephone call with new. We tin stone this pattern within a .mill():

                          office              PersonService              (              $http              )              {              part              Person              ()              {              this              .              foo              =              role              ()              {              };              }              Person              .              prototype              .              bar              =              function              ()              {              };              return              Person              ;              }              athwart              .              module              (              '              app              '              )              .              manufacturing plant              (              '              PersonService              '              ,              PersonService              );                      

Now, we have awesome power. Permit's inject our PersonService into a Controller and telephone call new PersonService(); to go a new example:

                          function              PersonController              (              PersonService              )              {              // new example!              var              newPerson              =              new              PersonService              ();              console              .              log              (              newPerson              );              }              angular              .              module              (              '              app              '              )              .              controller              (              '              PersonController              '              ,              PersonController              );                      

The output of the newPerson gives us access to the constructor foo property and also __proto__ where nosotros can access bar: role () {}. This is what factories exercise, they create new Objects in ways you want them to.

Conclusion

Both .service() and .manufactory() are both singletons every bit you'll only get one example of each Service regardless of what API created it.

Think that .service() is merely a Constructor, it's chosen with new, whereas .factory() is just a function that returns a value.

Using .factory() gives us much more ability and flexibility, whereas a .service() is essentially the "terminate result" of a .factory() telephone call. The .service() gives us the returned value by calling new on the function, which can be limiting, whereas a .manufactory() is one-step earlier this compile procedure every bit we get to choose which pattern to implement and render.

How To Get New Instance Of Service Angular 1.6,

Source: https://ultimatecourses.com/blog/factory-versus-service

Posted by: bramanmoafflurs.blogspot.com

0 Response to "How To Get New Instance Of Service Angular 1.6"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel