-3

I have a http service which will call external json files and load it into a grid.

My problem is i need to create a custom http service so that i could use the same in different controllers. The function of that custom service should be the same (requesting external Json file)

    $http.get('../JSON/permanentEmployees.json').
 success(function(data, status, headers, config) {
  $scope.masterArray = data;
 }).
 error(function(data, status, headers, config) {
   $scope.errorMessage = "Requested grid data file does not exist";
 });

This is my current http service. Any help would be appreciated.Please use angularjs only

Prag
  • 1
  • 1

1 Answers1

0

wrap the code in a factory and use it. I think its better to use a factory in this situation, refer here. P.S. unable to create a mockup of the request to JSON, please check with your JSON.

JSFiddle: here

app.factory('customHTTPService', function($http){
  return {
    getRequest: function(url) {
      return $http.get(url).
      success(function(data, status, headers, config) {
        return {data: data, errorMessage: "Success"};
      }).
      error(function(data, status, headers, config) {
        return {data: "", errorMessage: "Requested grid data file does not exist"};
      });
    } 
  }
});

In the controller you can do

app.controller('MyController', function MyController($scope, customHTTPService) {
    $scope.data = customHTTPService.getRequest('../JSON/permanentEmployees.json').data;
});    
Naren Murali
  • 19,250
  • 3
  • 27
  • 54
  • Thank you, it worked but i need to pass a different URL for the other controllers, how can i keep one factory method and keep changing the url for different controllers – Prag Aug 21 '17 at 08:01
  • @Prag I have updated my answer, next time specify all the details – Naren Murali Aug 21 '17 at 08:13