2016-11-20 71 views
0

我正在构建一个获取任何城市天气的简单天气应用程序。 对于这个API有两个阶段: 1)你输入一个城市的名字,得到它的“地球上的ID”(woeid)。 2)使用woeid搜索天气。将数据从metaweather API获取到angularjs页面

这是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="[email protected]" 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="[email protected]*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script> 
<script data-require="[email protected]*" 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> 

回答

1

看来你有一个跨源问题。它看起来不像Metaweather支持JSONP,所以修复这个有点复杂。您需要通过可支持代理的服务器运行您的页面。一个这样的例子是https://www.npmjs.com/package/cors-anywhere。如果设置了使用默认值,然后改变你的AJAX调用:

$http.get('http://localhost:8080/https://www.metaweather.com/api/location/search/?query=' + city)

+0

我会尝试。谢谢 –