如何通过AngularJS中的$ resource访问外部资源(JSON DATA)

时间:2017-05-30 06:45:26

标签: angularjs json

我正在尝试从openweathermap.org(JSON)中检索天气数据,

这是我的服务代码:

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;
    };

}]);

这是我的控制器代码:

weatherApp.controller('forecastController', ['$scope', '$log', 'forecastService', function($scope, $log, forecastService) {

    $log.info(forecastService.getWeather('Davao City', '5'));

}]);

Kept on getting this error, please help T_T

angular.min.js:123 TypeError: c.split is not a function
    at C.setUrlParams (http://127.0.0.1:50003/core-js/angular-resource.min.js:12:269)
    at Function.l.(anonymous function) [as get] (http://127.0.0.1:50003/core-js/angular-resource.min.js:10:156)
    at Object.getWeather (http://127.0.0.1:50003/project-js/forecast.factory.js:14:40)
    at new <anonymous> (http://127.0.0.1:50003/project-js/forecast.controller.js:3:31)
    at Object.instantiate (http://127.0.0.1:50003/core-js/angular.min.js:44:272)
    at http://127.0.0.1:50003/core-js/angular.min.js:94:141
    at Object.link (http://127.0.0.1:50003/core-js/angular-route.min.js:7:322)
    at http://127.0.0.1:50003/core-js/angular.min.js:17:3
    at ra (http://127.0.0.1:50003/core-js/angular.min.js:85:35)
    at n (http://127.0.0.1:50003/core-js/angular.min.js:70:226) "<div ng-view="" class="ng-scope">"

1 个答案:

答案 0 :(得分:1)

我知道为时已晚,但是我只是遇到了与您一样的问题并解决了。

我认为问题出在使用trustAsResourceUrl,当angular尝试拆分时,它以未定义的形式传递url,这会导致错误。

我只是将openweathermap域添加到白名单,然后创建没有trustAsResourceUrl的资源:

weatherApp.config(function($sceDelegateProvider){
    $sceDelegateProvider.resourceUrlWhitelist([
   // Allow same origin resource loads.
   'self',
   // Allow loading from openweathermap
   'http://api.openweathermap.org/**']);
});

然后创建资源:

$scope.weatherAPI = $resource("http://api.openweathermap.org/data/2.5/forecast", {get: {method: "JSONP"}});

请注意,我删除了{回调:“ JSON_CALLBACK”},这引起了另一个错误。

致谢。

相关问题