2017-05-30 81 views
0

我試圖從openweathermap.org(JSON)檢索天氣數據檢索外部資源(JSON),

這是我的控制器代碼:

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

}]); 

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">" 

回答

0

在你的情況下,weatherResult變量是一個promise對象。

myPromiseReturningServiceFunctionCall.$promise(successFunction(data) { 
      // Do something with the data. 
     }, errorFunction(error) { 
     } 
    ) 

所以你的情況的代碼應該是::您可以通過在控制器中得到$ HTTP調用的返回值

forecastService.getWeather('Davao City', '5').$promise(
     successFunction(data) { 
      // Do something with the data. 
     }, errorFunction(error) { 
     }) 

有關$資源的更多信息,你可以隨時參考docs 。返回部分將對此進行更多啓發。