0

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

2 Answers 2

2

.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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.