rebilliony rebilliony - 3 years ago 147
Javascript Question

How to make http call in service but get response by the controller? AngularJS

I`ve got a service where I call http,the problem is that I dont understand how to use $scope.photos in the controller.How to config controller and service to do this?

app.service('httpService',function($scope,$http){
function getAll() {
$http.get('/allphotos').then(function success(response) {
$scope.photos = response.data;
}, function error(err) {
console.log('error is:' + err.err)
});
}
});

app.controller('ctrl',function ($scope, httpService) {

}

Answer Source

First of all never use $scope inside Service/Factory/Provider. The scope is related to controllers only, a.e. deals with bind views with controllers.


You have a method getAll() that should return Promise and you will be able to resolve it inside your controller.

Something like:

app.service('httpService',function(,$http){
      this.getAll = function() {
        return $http.get('/allphotos').then(function(response) {
      //  ^ 'getAll' returns Original Promis comes from '$http'
            return response.data;
      //      ^  here we resolve 'response.data' 
        }, function(err) {
            console.log('error is:' + err.err)
        });
    }
});

And now in controller do:

app.controller('ctrl',function ($scope, httpService) {
   httpService.getAll().then(function(data) {
            $scope.data = data;
        }, function error(err) {
            console.log('error is:' + err.err)
        });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download