angularjsangular-httpangular-controllerangular-factory

Why do we use Factories/Services for ajax calls in Angularjs?


I was taught that we use factories/services to eliminate the duplicate coding. Here's a part of the code which works fine.

app.controller('ServicesCtrl',['$scope','DataFactory',function($scope,$http,DataFactory){

    DataFactory.GetData('services1.json')
      .then(function(response){
         $scope.returnedData = response.data;
    })
      .catch(function(response){
        console.log('Error in process',response.status,response.data);
    });
  }]);

app.controller('ContactCtrl',['$scope','DataFactory', function($scope,DataFactory){

    DataFactory.GetData('location.json')
      .then(function(response){
         $scope.returnedData = response.data;
    })
      .catch(function(response){
        console.log('Error in process',response.status,response.data);
    });
  }]);

app.factory('DataFactory',['$http',function($http){

  var factory = {};

  factory.GetData = function(path) {
    return $http.get(path);

  }
  return factory;
}]);

My question is 1. Why use services/factories to make such ajax calls when we have to work on the promises inside controllers? I mean, I have to make the same .then and .catch calls in both the controllers here. Where is the efficiency in it? Is there any better way to do this? Or am I doing this wrong? Is it possible to to work on those promises inside the factories and return the response.data to different controllers?


Solution

  • The thing here is re-usability of code . Now suppose you have a service called

    angular.module('test')
      .service('testService', function ($http) {
    
        this.getBidsUser = function ($username) {
          var endpoint = "bids/users/"+$username;
    
          return $http({
            method: 'get',
            url: endpoint
          });
        };
    
    }
    

    which returns bids of a user . You might want to use the same information in different views. So its a good idea to use service so that you dont have to rewrite same code again .

    Once more you might want to have all the same end point related service on the same service for maintainability .

    You might need to change end points for a service which will be hectic if you do not use service pattern .

    Promises arr call backs . If you process those promises inside a service it will not be easy to maintain caller timeline .