我正在构建一个简单的天气应用程序,可以获取任何城市的天气。 对于此API,有两个阶段: 1)你输入一个城市的名字,得到它的“地球ID”(woeid)。 2)使用woeid搜索天气。
这是API:https://www.metaweather.com/api/
例如: https://www.metaweather.com/api/location/search/?query=london 你得到这个JSON: [{ “标题”: “伦敦”, “LOCATION_TYPE”: “城市”, “WOEID”:44418 “latt_long”: “51.506321,-0.12714”}]
对于初学者来说,只是为了获得这个凶手会很棒。 它无法连接到API,但是当我手动输入它时,它可以工作。
app.js:
var app = angular.module('weatherApp', []);
app.controller('weatherCtrl', ['$scope', 'weatherService', function($scope, weatherService) {
function fetchWoeid(city) {
weatherService.getWoeid(city).then(function(data){
$scope.place = data;
});
}
fetchWoeid('london');
$scope.findWoeid = function(city) {
$scope.place = '';
fetchWoeid(city);
};
}]);
app.factory('weatherService', ['$http', '$q', function ($http, $q){
function getWoeid (city) {
var deferred = $q.defer();
$http.get('https://www.metaweather.com/api/location/search/?query=' + city)
.success(function(data){
deferred.resolve(data);
})
.error(function(err){
console.log('Error retrieving woeid');
deferred.reject(err);
});
return deferred.promise;
}
return {
getWoeid: getWoeid
};
}]);
的index.html:
<!DOCTYPE html>
<html ng-app="weatherApp">
<head>
<meta charset="utf-8" />
<title>Weather App</title>
<link data-require="bootstrap-css@3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script>document.write('<base href="' + document.location + '" />');</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script data-require="jquery@*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="weatherCtrl">
<form>
<div class="form-group">
<input class="form-control" type="text" ng-model="city" placeholder="e.g. london" />
<input class="btn btn-default" type="submit" value="Search" ng-click="findWoeid(city)" />
</div>
</form>
<p ng-show="city">Searching the forecasts for: {{city}}</p>
<div>
<h1>WOEID is: {{ place }}</h1>
<a ng-click="findWeather('london'); city = ''">reset</a>
</div>
</body>
</html>
答案 0 :(得分:1)
看来你有一个Cross Origin问题。它看起来不像Metaweather支持JSONP,因此对此的修复有点复杂。您需要通过可以支持代理的服务器运行您的页面。一个这样的例子是https://www.npmjs.com/package/cors-anywhere。如果使用默认设置进行设置,则将AJAX调用更改为:
$http.get('http://localhost:8080/https://www.metaweather.com/api/location/search/?query=' + city)