Может кто-нибудь сказать мне, почему я получаю следующее:
Внутри моего контроллера я делаю обычный вызов API, используя директиву Angular Resource.
$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' });
И распечатать результаты на консоли.
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);
Но вот результат. Как вы можете видеть, даже если объекты идут через $scope.weatherResult
когда я пытаюсь настроить таргетинг на один из его свойств, я получаю undefined
и, следовательно, не могу использовать эти данные.
Из Документов:
Важно понимать, что вызов метода объекта
$resource
немедленно возвращает пустую ссылку (объект или массив в зависимости отisArray
). Как только данные возвращаются с сервера, существующая ссылка заполняется фактическими данными
- Справочник по API ресурса AngularJS $
Используйте .then
метод $promise
имущества $resource
объекта для обеспечения функции в $q
сервис, который будет ждать данных, чтобы решить.
$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);
});