here 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 send data controlller using $http service inside custom service?
several problems $http
asynchronous , service method toptracks()
doesn't return anything. can't return inside success
, there return ... use then()
instead
you need return promise service , set scope in 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); }); } ]);
Comments
Post a Comment