【问题标题】:Angularjs, getting data from factoryAngularjs,从工厂获取数据
【发布时间】:2015-06-05 04:02:27
【问题描述】:

我有一家工厂,我试图通过 $http 服务获取数据。

工厂:

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

} })();

在控制器中我从工厂调用函数:

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

查看:

<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>

它工作但不正确。我必须单击按钮两次才能显示正确的数据。

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    当您发出任何服务器请求时,您必须等到响应在回调函数中可用。

    在您的代码中,您将立即从函数 GetWeather 返回,因此 weat 第一次为空。当您第二次单击该按钮时,届时天气信息将可用,因此您可以查看天气信息。

    您必须在代码中进行以下更改。

    服务变化

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

    控制器更改

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 2016-07-12
      • 2016-10-27
      • 1970-01-01
      • 2015-09-21
      相关资源
      最近更新 更多