2016-11-20 3 views
0

모든 도시의 날씨를 가져 오는 간단한 날씨 앱을 구축 중입니다. 이 API의 경우 두 단계가 있습니다. 1) 도시 이름을 입력하고 "where on earth ID"(woeid)를 가져옵니다. 2) 날씨를 검색하려면 woeid를 사용하십시오. 예를 들어 https://www.metaweather.com/api/metaweather API에서 angularjs 페이지로 데이터 가져 오기

:

이것은 API입니다 [{ "제목": "런던", "LOCATION_TYPE": "도시", "WOEID":이 JSON 얻을 https://www.metaweather.com/api/location/search/?query=london 44,418을, "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입니다. 내가 이것을 시도 할 것이다

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

+0

: 기본값을 사용하여 해당를 설정 한 경우 다음에 AJAX 호출을 변경합니다. 감사 –

관련 문제