Search code examples
angularjsangularjs-service

AngularJs Service called from two places returns same value


I am new to angular and pardon my ignorance if any. I am trying to create a simple service that will do a get funtionality and serve data into array. The problem i am having is, no mattter what i do - i always get the same data for any parameter i pass.

Here is my sample service

function myService($http, $q) {
    var service = {
        getSomeData: getSomeData:

    };
    var def = $q.defer();

    return service;

    function getSomeData(category) {


        if (category === 'books') {
            url = 'http://www.someurl1';
        } else {
            url = 'http://www.someurl2'
        };

        $http.get(url, {
            params: {
                'type': category
            }

        }).success(function(data) {
            def.resolve(data);
        }).error(function() {
            def.reject('Failed to get data');
        });
        return def.promise;
    }
}

})();

Once i have this, in my controller, i am trying to call it for sample purposes like this

$scope.someData = [] ;
$scope.someData.push(myService.getSomeData('DVDs'); 
$scope.someData.push(myService.getSomeData('books');

Now when i my look at my $scope.someData, i have an array of two objects - the problem being that they are always the same and doesnt have data specific to books and dvds.

Another minor issue I have is my object someData has

array --> Promise -- > $$state --> value

which then has the actual data. how can i get the data directly. i tried return def.promise(data);


Solution

  • One problem is you are only creating one promise outside the getSomeData function.

    A promise can only be resolved once. You need a new promise for each request.

    Also $http already returns a promise but you can't push it directly into an array as data.

    your code should look more like:

    Service:

    function myService($http, $q) {
      var service = {
        getSomeData: getSomeData
      };
    
    
      return service;
    
      function getSomeData(category) {
    
        if (category === 'books') {
          url = 'http://www.someurl1';
        } else {
          url = 'http://www.someurl2'
        };
    
        return $http.get(url, {
          params: {
            'type': category
          }
        }).then(function(response) {
          return response.data;
        }).catch(function(err) {
          console.log("Ooops", err)
        });
      }
    }
    

    Controller

    $scope.someData = [] ;
    myService.getSomeData('DVDs').then(function(data){
       data.forEach(function(item){
           $scope.someData.push(item);
       });
    });