0

I created a service that fetches data from local json and use it in a controller to display it in browser. All are working fine. here is my code:

JS Code:

var myApp = angular.module("myApp", ['ngRoute']);

myApp.service("dataService", function($http, $q){
   var deferred = $q.defer();
   $http.get('json/link.json').then(function(data){
        deferred.resolve(data);
    });

   this.getData = function(){
     return deferred.promise;
   }
})
.controller("linkCtrl", function($scope, dataService) {
    var promise = dataService.getData();
    promise.then(function(data) {
        $scope.links = data.data;
    });
});

Now, i have another json link (for eg.: json/link2.json ) and i want to perform the same function. Is there any way to use the "dataService" service ( like changing the link ).

I don't want to re-create a new service which does the same function. Any idea to re-use the Service for different json data ?

Thanks in Advance

2
  • Have you tried passing the URL to the service? Commented Sep 2, 2015 at 14:57
  • Do you need to cache the promise? Commented Sep 2, 2015 at 14:59

2 Answers 2

1

Just create a method you can pass url to:

myApp.service("dataService", function($http){
   this.getData = function(url){
      return $http.get(url); // this returns a promise
   };
})

Use it like this:

.controller("linkCtrl", function($scope, dataService) {
    var promise1 = dataService.getData('json/link.json');
    promise1.then(function(data) {
        $scope.links = data.data;
    });

    var promise2 = dataService.getData('json/link2.json');
    promise2.then(function(data) {
        $scope.links2 = data.data;
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Try something like this

myApp.service("dataService", function($http){
 this.getData = function(link,callback){
 $http.get(link).then(function(data){
    if(callback)
      callback(data);
   });
});
myApp.controller("linkCtrl", function($scope, dataService) {
    dataService.getData('json/link.json', function(data){
      $scope.links = data.data;
    });
});

2 Comments

can you explain the service function used here?
i defined service function with a callback function and a link param. after http.get returns some thing from link we provided we check callback funciton. if it exists we call it with data. on controller we are calling getData function of service with link and a function and we say that function expects a parameter. now callback = function(data) etc... and service used that callback function now that data value is comes from service

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.