Learn Services, Factories and Providers in angularjs From Scratch

Services, providers, and factories are all just fancy ways of saying “library”. A broad description of a library would be some collection of behavior that is reusable across multiple codebases. Services provide this by acting as an instantiated, singleton object, likely full of many instance methods. Factories can provide a new object every time, perhaps full of functions, or perhaps just a single function, or even object. Providers act much like factories, but they are configurable before angularjs hits its “run” phase.

Controllers, filters, directives etc., can all use these via DI (dependency injection). You can share functions, models, singleton objects, classes (or just about anything) between disparate components. These controllers, filters, and directives can be considered the codebases your libraries provide behavior to.

You must understand the differences between services, factories, and providers. You must also understand when to use them. Here’s a table to oversimplify the situation:

Component Instantiated Needs a $get method Explicitly returns something Present during config()
Service Yes No No No
Factory No No Yes No
Provider Yes Yes No Yes

Our blog could also use a service, Posts, to handle our data. Here it is:

 // Define our first service; Posts
// This service simply uses the built-in $http service to retrieve data from
// a static JSON store.
blog.service('Posts', function ($http) {
    this.getPosts = function () {
       return $http.get('data.json');

Within the Posts service, there’s a getPosts() method which returns a promise from an $http call. We could have just put the $http call within the controller itself, but it’s good practice to put potentially reusable code into a service, since controllers cannot talk to one another unless they share the same scope. Now, any controller that injects Posts into itself can use the method here; we don’t have to write separate $http calls.

Of note, $http itself is a service. It’s built in to angularjs, and is one of a number of prerolled services for common functionality. We will discuss Ajax further in a bit.


About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest