Aditya Gupta
Aditya Gupta

Reputation: 79

service does not return data to controller in angular

Here is my service:

app.service('trackService', ['$http', function($http) {
    var data;
    this.topTracks = function(limit) {
        $http({
            method: 'GET',
            url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
            params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
        }).success(function(result) {
            this.data = result.tracks; console.log(this.data); return this.data;
        }); 
    }
}]);

and controller -

app.controller('artistSongsCtrl', ['$scope', 'trackService', function($scope, trackService) {
    $scope.data = trackService.topTracks(10);
    //console.log($scope.data);
}]);

how to send data to the controlller using a $http service inside a custom service?

Upvotes: 2

Views: 614

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Several problems are $http is asynchronous and your service method topTracks() doesn't return anything. Also you can't return inside success, there is nowhere to return to ... use then() instead

You need to return the promise from service and set the scope in a promise callback in controller

app.service('trackService', ['$http',
  function($http) {
    var data;
    var self = this;
    this.topTracks = function(limit) {
      return $http({
        method: 'GET',
        url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
        params: {
          api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf',
          format: 'json',
          limit: limit
        }
      }).then(function(result) {
        self.data = result.data.tracks;
        console.log(self.data);
        return self.data;
      });
    }
  }
]);

app.controller('artistSongsCtrl', ['$scope', 'trackService',
  function($scope, trackService) {
    trackService.topTracks(10).then(function(data) {
      $scope.data = data;
      //console.log($scope.data);
    });

  }
]);

Upvotes: 3

Asaf David
Asaf David

Reputation: 3297

Inside your service you are making an asynchronous GET request. In order to let the controller catch that response, you need to return a promise. Here's an example using $q:

app.service('trackService', ['$http', '$q', function($http, $q) {
    var data;
    this.topTracks = function(limit) {
        var d = $q.defer();
        $http({
            method: 'GET',
            url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks',
            params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json', limit: limit}
        }).success(function(result) {
            this.data = result.tracks; 
            console.log(this.data); 
            d.resolve(this.data);
        }); 
     return d.promise;
    }
}]);

Upvotes: 2

Related Questions