Henrique Henrique - 5 months ago 7
AngularJS Question

AngularJS $http request not updating the view

I am trying to update my view with a button click or with an $interval in AngularJS, I already manage to make the request work and to get the data that I needed but now that I want to make the page more dynamic I can't manage to update the view every time a user presses the button.

I am using OpenWeather API to get Weather.

To test if the view is updating I am defining two ID's, starting with London ID and then changing it to the ID of Paris.

var WEATHER_URL = 'http://api.openweathermap.org/data/2.5/weather';
var API_KEY = 'myAPI';
var LANG = 'en';
var MODE = 'json'
var UNITS = 'metric';

var ID = 2643743; // London ID


Then, I set the request parms:

var requestWeather = {
method: 'GET',
url: WEATHER_URL,
params: {
id: ID,
mode: MODE,
units: UNITS,
appid: API_KEY,
lang: LANG
}
};


And I make a function to do the request:

function retrieveWeather() {
$http(requestWeather)
.then(function(response) {
$scope.weather = response.data;
}).
catch(function(response) {
$scope.weather = response.data;
});
}
retrieveWeather(); // Request on page load


I have an update function to test if the view updates whenever I change the ID of the city:

$scope.update = function() {
ID = 2988507; // Change to ID of Paris
retrieveWeather();
console.log(ID); // <-- This prints the ID in the console, so, the function is called
};


This is my view:

<p>{{weather}}</p>
<button ng-click="update()">Update</button>


When I click the update button nothing changes on the view, it should do another call changing the city ID, but nothing...

Thank you.

Answer
Make sure your latest is updating in URL or not otherwise your code is working fine. You can try by putting your id directly in requestWeather variable.

var requestWeather = {
    method: 'GET',
    url: WEATHER_URL,
    params: {
      id: 2988507, // Change to ID of Paris,
      mode: MODE,
      units: UNITS,
      appid: API_KEY,
      lang: LANG
    }
  };
Comments