Issue
Trying to  understand how AngularJS works, doing my first API calls, when I got stuck.
I want to do 2 API calls, but I can't seem to make it work.  
After the first $http.get I want to do an another call (using the information from the previous call) but that doesn't work for some reason. (I get no alert)
The city and country are working perfectly after the first .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>
Solution
You can use promise to call the request after another which is the recommended way to do,
Another thing is you are missing the http part in the second request
Code:
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);
            })
    }
})
Answered By - Sajeetharan
 
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.