我正在構建一個獲取任何城市天氣的簡單天氣應用程序。 對於這個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>
我會嘗試。謝謝 –