0

I have a factory where i am trying to get data by $http service.

factory:

(function(){
angular
.module('projectApp')
.factory('weatherfactory', weatherfactory);

weatherfactory.$inject=['$http'];

function weatherfactory($http){
var cities=[
  {name: "Łódź", link: "http://api.openweathermap.org/data/2.5/weather?q=Lodz,pl"},
  {name: "Warszawa", link: "http://api.openweathermap.org/data/2.5/weather?q=Warszawa,pl"}

];
var weat={};

var service={
  getCities: getCities,
  GetWeather: _GetWeather
};
return service;

function _GetWeather(link){
  $http.get(link).success(function(data){
    weat=data;
  });
  return weat;
}


function getCities(){
  return cities;
}

} })();

In controller i call function from factory:

function weatherData(city){
  sa.weather=weatherfactory.GetWeather(city);
  sa.show=true;
}

View:

<div class="row">
    <div class="col-md-8">
      <select class="form-control" ng-model="sa.city">
        <option ng-repeat="city in sa.cities" value="{{city.link}}">{{city.name}}</option>
      </select>
    </div>
    <div class="col-md-4">
      <button class="btn btn-primary" ng-click="sa.weatherData(sa.city)">Wybierz</button>
    </div>
    <div ng-if="sa.show">
      {{sa.weather.name}}
    </div>
  </div>

It works but not correctly. I have to click button twice to show correct data.

1 Answer 1

1

When you make any server request you have to wait until the response is available in the callback function.

In your code you are right away returning from the function GetWeather so weat is empty for the first time. When you click the button second time the weather information is available by that time so you are able to see the weather information.

You have to do the below changes in your code.

Service change

function _GetWeather(link){
  return $http.get(link);
}

Controller change

function weatherData(city){
   weatherfactory.GetWeather(city).success(function (data) {
        sa.weather = data;
        sa.show = true;
   });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.