简体   繁体   中英

Angularjs, getting data from factory

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.

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;
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM