如何通过AngularJS$resource检索外部资源(JSON)
我试图从openweathermap.org(JSON)检索天气数据 这是我的控制器代码:如何通过AngularJS$resource检索外部资源(JSON),angularjs,Angularjs,我试图从openweathermap.org(JSON)检索天气数据 这是我的控制器代码: weatherApp.controller('forecastController', ['$scope', '$log', 'forecastService', function($scope, $log, forecastService) { $log.info(forecastService.getWeather('Davao City', '5')); }]); 这是我的服务代码:
weatherApp.controller('forecastController', ['$scope', '$log', 'forecastService', function($scope, $log, forecastService) {
$log.info(forecastService.getWeather('Davao City', '5'));
}]);
这是我的服务代码:
weatherApp.service('forecastService', [ '$resource', '$sce', function
($resource, $sce) {
this.getWeather = function (city, numDays){
var key = 'b3cc85931eae059522f3a9b8c5260f6e';
var link = function() {
return $sce.trustAsResourceUrl("http://api.openweathermap.org/data/2.5/forecast/");
};
var weatherAPI = $resource(link(), { callback: "JSON_CALLBACK" }, { get: { method: "JSONP" }});
var weatherResult = weatherAPI.get({ q: city, cnt: numDays, appid: key });
return weatherResult;
};
}]);
angular.min.js:123类型错误:c.split不是函数
在C.seturlparms处(http://127.0.0.1:50003/core-js/angular resource.min.js:12:269)
at Function.l.(匿名函数)[as get](http://127.0.0.1:50003/core-js/angular resource.min.js:10:156)
在Object.getWeather(http://127.0.0.1:50003/project-js/forecast.factory.js:14:40)
在纽约(http://127.0.0.1:50003/project-js/forecast.controller.js:3:31)
在Object.instantiate(http://127.0.0.1:50003/core-js/angular.min.js:44:272)
在http://127.0.0.1:50003/core-js/angular.min.js:94:141
在Object.link(http://127.0.0.1:50003/core-js/angular route.min.js:7:322)
在http://127.0.0.1:50003/core-js/angular.min.js:17:3
在ra(http://127.0.0.1:50003/core-js/angular.min.js:85:35)
在n(http://127.0.0.1:50003/core-js/angular.min.js:70:226)”
在您的示例中,weatherResult变量是一个promise对象。您可以通过以下方式在控制器中获取$http调用返回值:
myPromiseReturningServiceFunctionCall.$promise(successFunction(data) {
// Do something with the data.
}, errorFunction(error) {
}
)
因此,在您的情况下,代码应该是:
forecastService.getWeather('Davao City', '5').$promise(
successFunction(data) {
// Do something with the data.
}, errorFunction(error) {
})
有关$resource的更多信息,请始终参阅。返回部分将对此有更多的启发
forecastService.getWeather('Davao City', '5').$promise(
successFunction(data) {
// Do something with the data.
}, errorFunction(error) {
})