Reputation: 576
Can someone tell me why I'm getting the following:
Inside my controller I'm doing a normal call to an API using the Angular resource directive.
$scope.weatherAPI = $resource('http://api.openweathermap.org/data/2.5/forecast/daily', {callback: 'JSON_CALLBACK'}, {get: {method: 'JSONP'}});
$scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 4, APPID: 'xxxxxx' });
And printing the results to the console.
console.log($scope.weatherResult);
console.log($scope.weatherResult.city)
console.log("scope weatherResult " + $scope.weatherResult);
console.log("scope weatherResult.list: " + $scope.weatherResult.list);
console.log("scope weatherResult.city: " + $scope.weatherResult.city);
But here is the result. As you can see even though the objects are coming thru with $scope.weatherResult
when I try and target one of its properties I get undefined
, and hence am unable to use that data.
Upvotes: 0
Views: 114
Reputation: 48968
From the Docs:
It is important to realize that invoking a
$resource
object method immediately returns an empty reference (object or array depending onisArray
). Once the data is returned from the server the existing reference is populated with the actual data
-- AngularJS $resource API Reference
Use the .then
method of $promise
property of the $resource
object to supply a function to the $q
service that will wait for the data to resolve.
$scope.weatherAPI = $resource('http://api.openweathermap.org/data/2.5/forecast/daily', {callback: 'JSON_CALLBACK'}, {get: {method: 'JSONP'}});
$scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 4, APPID: 'xxxxxx' });
$scope.weatherResult.$promise.then (function onFulfilled(data) {
console.log(data);
console.log(data.city);
console.log("scope weatherResult " + $scope.weatherResult);
console.log("scope weatherResult.list: " + $scope.weatherResult.list);
console.log("scope weatherResult.city: " + $scope.weatherResult.city);
});
Upvotes: 1