javascript - AngularJS + API 调用

标签 javascript angularjs api

尝试了解 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/

相关文章:

python - 使用 urllib2 下载网页导致乱码垃圾? (只是有时)

c# - 如何构造C#类库?

javascript - Angular Material select 在固定 block 上的行为很奇怪

javascript - 使用嵌套对象属性过滤 ng 重复在 Angularjs 应用程序中不起作用

javascript - $$ ('foo' ) 在 JavaScript 源代码中是什么意思?

javascript - 如何使 "ActiveXObject(' SAPI.SpVoice')"在 Firefox 中工作

javascript - 未占用空间中的额外元素选择框(HTML/JS/CSS w/Angular.js)

javascript - 使用回调在 fb.api 之外获取值变量

javascript - C++ - 实现 JS 的 setTimeout 的现代方法

javascript - setInterval 是否重复?