2015-06-14 24 views
0

我使用openweathermap api獲取json數據,我需要獲取並使用jsonp數據,如何在我的角度服務中做到這一點?角度。如何確定json響應jsonp響應?

app.factory('forecast', ['$http', function($http) { 
    this.sendAPIRequest = function(city){ 
     return $http.get('http://api.openweathermap.org/data/2.5/forecast/city?q='+city+'&units=metric&mo') 
     .success(function(data) { 
      return data; 
     }) 
     .error(function(err) { 
      return err; 
     }); 
    }, 

回答

1

https://docs.angularjs.org/api/ng/service/ $ http#jsonp演示使用angular接收JSONP對象的正確方法。

的$ HTTP服務調用(從AngularDocs)看起來像:

$http({method: 'JSONP', url: $scope.url, cache: $templateCache}) 
    .success(function(data, status) { 
     $scope.status = status; 
     $scope.data = data; 
    })... 

雖然標記結合這個功能是:

<div ng-controller="FetchController"> 
    <select ng-model="method" aria-label="Request method"> 
    <option>GET</option> 
    <option>JSONP</option> 
    </select> 
    <input type="text" ng-model="url" size="80" aria-label="URL" /> 
    <button id="fetchbtn" ng-click="fetch()">fetch</button><br> 
    <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> 
    <button id="samplejsonpbtn" 
    ng-click="updateModel('JSONP', 
        'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')"> 
    Sample JSONP 
    </button> 
    <button id="invalidjsonpbtn" 
    ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')"> 
     Invalid JSONP 
    </button> 
    <pre>http status code: {{status}}</pre> 
    <pre>http response data: {{data}}</pre> 
</div> 

所以基本上你的最終結果將是:

app.factory('forecast', ['$http', function($http) { 
    this.sendAPIRequest = function(city){ 
     return $http.jsonp('http://api.openweathermap.org/data/2.5/forecast/city?q='+city+'&units=metric&mo') 
     .success(function(data) { 
      return data; 
     }) 
     .error(function(err) { 
      return err; 
     }); 
    }, 

如在這裏看到的那樣:parsing JSONP $http.jsonp() response in angular.js

+0

你是awesowe它的工作,現在我可以移動一個工作:) – Michal