我使用openweathermap api获取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;
});
},
答案 0 :(得分: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;
});
},