2017-03-11 42 views
2

试图了解AngularJS如何工作,如何进行我的第一次API调用,何时卡住。
我想做2个API调用,但我似乎无法使其工作。AngularJS + API调用

在第一个$ http.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> 
+2

我认为你需要http协议添加到您的第二个URL。 – artemisian

+0

是的。你认为恰到好处..我的尴尬.. – Aiden

回答

2

你可以用承诺来调用接下来的要求是推荐的做法,

另一件事是你错过了在第二个请求荷兰国际集团的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); 
      }) 


    } 

}) 
+0

只是一个问题。 $ scope.makeRequest的目的是什么?仅仅调用infoReq()是不够的? – Aiden