Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I am trying to get data back from a web service, I have to approaches the first is calling the data from the controller which works here is the code

$http({
method: 'POST',
url: 'https://url_json.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset-UTF-8'},
transformRequest: function(obj) {
    var str = [];
    for(var p in obj)
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
},
  data: paramsVal
}).then(function(response){

$scope.myData = response.data.PlaceDetailsResponse.results[0].first_name;

console.log('my data',$scope.myData);
});

}

but I would like to share the data between controllers so I read service is the best options, so in my services.js I have:

.factory('userService', function($http){
return {
    getUsers: function(){
        return $http.post("https://url_json.php",
            {entry : 'carlo' ,
            type:'first_name',
            mySecretCode : 'e8a53543fab6f00ebec85c535e' 
        }).then(function(response){

            users = response;
            return users;
        });
    }
}

})

but when I call it from the controller with var user = userService.getUsers(); returns the below in the console:

user is [object Object]

and inspecting element within chrome I only see:

user is Promise {$$state: Object}

Also in chrome when I drill down on Promise the data value = "".

Can anyone take a look at my services and see if I'm doing anything wrong.

Thanks

share|improve this question
up vote 2 down vote accepted

.then returns a promise. You're falling for the explicit promise construction antipattern.

getUsers: function(){
    return $http.post("https://url_json.php",
        {entry : 'carlo' ,
        type:'first_name',
        mySecretCode : 'e8a53543fab6f00ebec85c535e' 
    })
}

The above is all you need. Then, in your controller:

userService.getUsers()
.then(function(response) {
  $scope.data = response.data; // or whatever
});

I would recommend looking at John Papa AngularJS style guide. He has a lot of information about fetching service data, using it in controllers, etc.

share|improve this answer

In your controller you will have to assign the user variable by resolving the promise return from the getUsers like below:

$scope.user = [];
$scope.error ="";

userService.getUsers().then(function(data){
  $scope.user = data
},function(err){
   $scope.error = err; 
});

Hope this helps.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.