MOCKSTACKS
EN
Questions And Answers

More Tutorials









Angular Service vs Factory


By definition:

Services are basically constructor functions. They use ‘this’ keyword.
Factories are simple functions hence return an object.

Under the hood:

Factories internally calls provider function.
Services internally calls Factory function.

Debate:

Factories can run code before we return our object literal.
But at the same time, Services can also be written to return an object literal and to run code before returning.
Though that is contra productive as services are designed to act as constructor function.
In fact, constructor functions in JavaScript can return whatever they want.

So which one is better?

The constructor syntax of services is more close to class syntax of ES6. So migration will be easy.

Summary

So in summary, provider, factory, and service are all providers.
A factory is a special case of a provider when all you need in your provider is a $get() function. It allows you to write it with less code.
A service is a special case of a factory when you want to return an instance of a new object, with the same benefit of writing less code

Conclusion

In this page (written and validated by ) you learned about AngularJS Service vs Factory . What's Next? If you are interested in completing AngularJS tutorial, your next topic will be learning about: AngularJS promises with q.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.