使用外部API进行天气预报

时间:2015-02-02 17:04:43

标签: angularjs api rest weather-api

我正在尝试使用openweathermap.org的外部API获取天气预报,并且想要使用angular.js到目前为止我能够在不使用API KEY的情况下获得单个城市的预测并尝试获得预测在API Key的帮助下多个城市,因为我无法通过api密钥找到正确的方法

所以这里清楚地描绘了我想要做的事情

1.该应用应接受用户的多个城市名称 2.根据输入的城市名称,应用程序应显示每个城市14天的天气预报

var artistControllers = angular.module('artistControllers', []);

var apiKey = '89b59e4d7d07894243b5acd24e7f18a3';
artistControllers.controller('WController', ['$scope', '$http', function($scope, $http) {
console.log('ijij');
$http.jsonp('api.openweathermap.org/data/2.5/forecast/daily?id=524901').success(function(err,data){
if(err){
  console.log(err);
}
$scope.data=data;
console.log(data);
});
}]);

1 个答案:

答案 0 :(得分:3)

在文档中说:

  

如何使用API​​密钥

     

将以下参数添加到GET请求:   APPID=APIKEY
  例:   api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=1111111111

     

或者将以下行添加到服务器的http标头:   x-api-key:APIKEY

所以你可以通过在$ http调用中的url后面附加API密钥来使用。

请参阅:http://openweathermap.org/appid

或者,正如文档所述,您可以在HTTP请求中添加额外的标头。你可以在AngularJS中这样做:

var req = {
 method: 'GET',
 url: 'api.openweathermap.org/data/2.5/forecast/daily?id=524901',
 headers: {
   'x-api-key': '89b59e4d7d07894243b5acd24e7f18a3'
 }
}

$http(req).success(function(){...}).error(function(){...});

链接:https://docs.angularjs.org/api/ng/service/ $ http

相关问题