Storm Storm - 3 months ago 10
AngularJS Question

How to correctly pass data from Service to Controller

I am trying to send data from my http service to my controller. The service correctly gets the data but it doesn't get sent to the controller.

Now, I am aware that the query is done asynchronously which is why I am trying to use $q.defer.
I tried following the example provided by a similar question : AngularJS $http call in a Service, return resolved data, not promises , however it still doesn't work.

Here is my Service :

.service("builds", ['$http', '$q', function($http, $q) {
var deferred = $q.defer();

$http({
method:'GET',
url: '/builds',
cache : true
}).success(function(data) {
deferred.resolve(data);
}).error(function(msg){
deferred.reject(msg);
});
console.log(deferred.promise);
return deferred.promise;}]);


And here is my routeProvider

$routeProvider.
when('/builds', {
controller: ['$scope', 'buildsData', function ($scope, buildsData) {
console.log("In routeprovider:" + buildsData);
$scope.allBuilds = buildsData;
}],
template: '<build-list></build-list>',
resolve: {
buildsData: ['builds', function(builds){
return builds;
}]
}
})


And finally here is a snippet of my Controller :

var app = angular.
module('buildList').
component('buildList', {
templateUrl: 'build-list/build-list.template.html',
controller: function BuildListController($scope, $window,$location,$cookies, builds) {
console.log($scope.allBuilds);
$scope.league = $scope.allBuilds;

Answer

As @vishal says

You should create a method in service because generally a service may have many get and set methods ( I mean best practice).

create a function say getData

function getData()
{
  $http({
      method:'GET',
      url: '/builds',
      cache : true
  })
}

then you should be calling this method in controller

In the controller you should inject this service and then

builds.getData().then(function(s){
//result

},function(e){

//error
}
);