Quantcast
Channel: TechieDreams
Viewing all articles
Browse latest Browse all 21

AngularJS Part 4 – Factories and Services

$
0
0

Earlier in this tutorial series we learnt about how to set up Angular Project and to work with ‘Controllers‘ and’Routing‘. In this tutorial we will move on to ‘Services/Factories’.

Note: ‘Service’ as generic word for both ‘Factory’ or ‘Service’. Don’t get confused!

Generally ‘Services/Factories’ can be used as a singleton data providers for the Angular App. We can make Http calls or any other data related operations in the services and can return the resolved data. Most generally services will hide the complexity of dealing wth data layer from the business layer(where we only focus on the implemention and business logic).

In this tutorial will check how both Services and Factories work with examples and what is the difference between these.

Factories:

A factory can be created using the ‘factory’ keyword. Syntax is as follows:

module.factory('factoryName', ['dependency1', 'dependency2', function(dependency1, dependency2) {
 	return {
 		sampleFunc1: function() {
 		},
 		sampleData: '',
 		sampleFunc2: function() {
 		}
 	}
 }]);

So from the above syntax we can understand that, a factory returns a JSON object which may contain functions or some data, these can be accessed by using the keys(Ex: to access ‘sampleFunc1′ the syntax will be ‘factoryName.sampleFunc1‘).

Example:

var serviceModule = angular.module('serviceApp.services', []);
serviceModule.factory('sampleFactory', ['$http', function($http) {
        return {
            getContacts: function() {
                return $http.get('data/myContacts.json');
            }
        };
    }]);

$http:

$http is a Angular service which provides an interface to access all the HTTP operations. In the above example we made a get request to the local data in the app.

One important thing here to note is $http will always return a promise. (‘promise’ –  The call back that would be called when the request is resolved.) So in the above example our factory method ‘getContacts’ returns a promise. Lets check how to resolve this promise.

Actually $http has will provide two callback functions, one on success and othe on failure. Here is the example where we call this factory function from our controller:

var controllerModule = angular.module('serviceApp.controllers', []);
controllerModule.controller('factoryController', ['$scope', 'sampleFactory', function($scope, sampleFactory) {
        sampleFactory.getContacts().success(function(data) {
            // console.log("data: " + JSON.stringify(data));
            $scope.employees = data;
        }).error(function(error) {
            // console.log("error: " + JSON.stringify(error));
        });
    }]);

So very first thing to do before calling a service is to inject it as shown in the example above. The above example demonstrates how to use the callbacks and read the responses.

In the Example above our factory is making a local service call to get the employees data and returning the promise to our controller, Where on success we are getting the results and logging it. We also setting the response to the modal which I’m displaying in the list. (Run the plunker example to check the results).

Now lets move on to Services.

Services:

Services are most similar to Factories just a minor change in the syntax. We can create a service using the ‘service’ keyword. Following is the syntax to write a Service:

module.factory('serviceName', ['dependency1', 'dependency2', function(dependency1, dependency2) {
 	return {
 		sampleFunc1: function() {
 		},
 		sampleData: '',
 		sampleFunc2: function() {
 		}
 	}
 }]);

Example:

var serviceModule = angular.module('serviceApp.services', []);
serviceModule.service('sampleService', ['$http', function($http) {
        this.getContacts = function() {
            return $http.get('data/myContacts.json');
        };

    }]);

And the we can use the Service in the same way as the Factories. So now lets know the difference between these.

Services VS Factories:

Though functionally both the Services and Factories act the same, the difference comes with the return type of these.
Service will return you with the intance of the it (this), through which you can access the service members. Factory will return you with a static object which rather can be treated as normal JSON object where you can access the factory members  as you access values in a normal JSON object.

When to use Service to a Factory:

Most commonly we use a Factory, as it is the normal javascript function way.
Optionally when you need to return the instance of the function we prefer Services.

Few bullet points:

  • Both Services and Factories are singletons.
  • Factories returns you the value.
  • Services returns you the instantiated object (this).
  • Services are only instantiated when they are injected and application component depends on it.
  • Factories are more preferable to Services, as they are just normal JavaScript functions and we write complex logic’s.
  • Services are more preferable when dealing with custom types (Objected oriented JavaScript)

Here is a simple Plunker Example on what a Service and Factory returns.

Live Demo:

Now got to know the difference between a Factory and Service and how and when to use one.

Final example:
Here I wrote an example to demonstrate how we can list some contacts from a HTTP service using Service and Factory.

Download the code zip:

Live Demo:

 

In the upcoming tutorials will continue with the other components with example for each one.

Subscribe, like and stay tuned!

The post AngularJS Part 4 – Factories and Services appeared first on Techie Dreams.


Viewing all articles
Browse latest Browse all 21

Trending Articles