尝试了解 AngularJS 的工作原理,进行我的第一次 API 调用,但遇到困难。
我想进行 2 个 API 调用,但我似乎无法使其工作。
在第一个 $http.get 之后,我想进行另一个调用(使用上一个调用的信息),但由于某种原因它不起作用。 (我没有收到警报)
在第一个 .get 之后,城市和国家运行良好
JS:
var app = angular.module('weather', []);
app.controller("weatherCtrl", function($scope, $http) {
$http.get("http://ipinfo.io/json").then(function(response) {
$scope.city = response.data.city;
$scope.country = response.data.country;
var apiKey = "";
var apiCall = "api.openweathermap.org/data/2.5/weather?q=" + response.data.city + "&APPID=" + apiKey;
$http.get(apiCall).then(function(responsew) {
// $scope.temperature would get a value here
alert("1")
});
});
})
HTML:
<body ng-app="weather" ng-controller="weatherCtrl">
<h1 class="text-center">Weather</h1>
<h2 class="text-center">{{city}}, {{country}}</h2>
<h2 class="text-center">{{temperature}} °C</h2>
</body>
最佳答案
您可以使用 promise 一个接一个地调用请求,这是推荐的方法,
另一件事是您在第二个请求中缺少 http
部分
代码:
app.controller("weatherCtrl", function ($scope, $http) {
function infoReq() {
return $http({
method: 'Get',
url: 'http://ipinfo.io/json'
})
}
function weatherReq() {
var apiKey = "";
var apiCall = "http://api.openweathermap.org/data/2.5/weather?q=" + $scope.city + "&APPID=" + apiKey;
return $http({
method: 'Get',
url: apiCall,
})
}
$scope.makeRequest = function () {
infoReq()
.then(function (response) {
$scope.city = response.data.city;
$scope.country = response.data.country;
return weatherReq();
})
.then(function (response) {
console.log(response.data);
})
}
})
关于javascript - AngularJS + API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42731829/