Sri Chatala Sri Chatala - 2 months ago 6
HTTP Question

Unable to make a list of http get calls through one service in angularjs to handle exceptions?

Process:
I try to call 4 httpget call though one httpGet method in a service, my first httpget call return an error and the rest of the calls return success message.

issues: I try to call that error function response to my controller but through console error TypeError:errorFunction is not a function

enter image description here

Code:

myController:

app.controller('myCtrl',["myService",function(myService){
var id =10;
$scope.getTemp = function () {
myService.getTemplate(id, $scope.getTemplateResponse, $scope.ErrorResponse);
};
$scope.getTemplateResponse= function (response) {
$scope.bodyTemplate = response.Value;
};
$scope.ErrorResponse = function(error){
window.location.href = "Error#?" + error;
}
$scope.getTemp ();
}]);


myService:

app.service("myService", ["ajaxService", function (ajaxService) {
this.getTemplate= function (id, successFunction, errorFunction) {
ajaxService.Get("http://gettempaltes.com/api/id="+id, successFunction, errorFunction);
};
}]);


ajaxService:

app.service("ajaxService", ["$http", function($http) {
this.Get= function (route, successFunction, errorFunction) {
$http.get(route).success(function (response, status) {
successFunction(response, status);
}).error(function(response) {
errorFunction(response);
});
};
}]);

Answer

Define $scope.ErrorResponse before you point to it. Like this

$scope.ErrorResponse = function(error)
{
  window.location.href = "Error#?" + error;
}

$scope.getTemp = function () 
{
  myService.getTemplate(id, $scope.getTemplateResponse, $scope.ErrorResponse);
};

Validate success/error fn's have been passed in before using them. Like this

app.service("ajaxService", ["$http", function($http) 
{
  this.Get= function (route, successFunction, errorFunction) 
  {
    $http.get(route)
      .success(function (response, status) 
      {
        if(angular.isFunction(successFunction))
        {
          successFunction(response, status);
        } 
      })
      .error(function(response) 
      {
        if(angular.isFunction(errorFunction))
        {
          errorFunction(response);
        }
      });
  };
}]);
Comments