Currently, I am working on retrieving data from a web service, and I have two approaches. The first approach involves calling the data from the controller, which is functioning correctly with the following 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);
});
}
However, I am interested in sharing this data between controllers. After researching, I found that using services would be the most suitable option. In my services.js file, I have included the following:
.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;
});
}
}
})
When I attempt to call this service from the controller using
var user = userService.getUsers();
, it returns the following output in the console:
user is [object Object]
Upon inspecting the element within Chrome, I only see:
user is Promise {$$state: Object}
Furthermore, when I drill down on the Promise object, the data value appears as an empty string.
If anyone could review my services code and point out any potential mistakes, I would greatly appreciate it.
Thank you.