将$ http数据从服务传递到控制器(异步)

时间:2016-02-26 15:41:54

标签: angularjs api asynchronous

我通过制作天气应用来学习Angular。所以,在index.html中我有一个下拉列表。

<select ng-model="city" ng-options="city.cityName for city in cities" ng-change="getWheather()">
    <option value=""></option>
</select>

根据用户从该列表中选择的城市,他会获得天气预报。当函数getWheather()在控制器中时,它完全正常工作。一旦我将它放入工厂,就不再有效了。我认为它是因为它是异步的,但我没有运气来修复它。

这是工厂(在网址中,数字45和15应该是city.latitcity.longit,但是我无法使其工作。如果我传递值&#34; city&#34;运行getWheather(),它是未定义的):

app.factory('wheatherService', function($http) {
  var getWheather = function(){
    var url ="https://api.forecast.io/forecast/api_key/"+45.815+","+15.966+"?callback=JSON_CALLBACK";
      return $http.jsonp(url);
  };

  return {
    getWheather: getWheather
  };
});

这是控制器:

app.controller('inputCtrl', function($scope, wheatherService){
  $scope.cities = [{ "cityName" : 'Paris', "latit" : 45.815399, "longit" : 15.966568},
                   { "cityName" : 'London', "latit" : 45.328979, "longit" : 14.457664},
                   { "cityName" : 'NewYork', "latit" : 43.510742, "longit" : 16.437489 }];

  wheatherService.getWheather().success(function(data){
    $scope.wheatherData = data;
      console.log($scope.wheatherData);
  });
});

所以主要的问题是 - 是否存在从下拉列表中获取选定值到getWheather()函数的方法是什么?

3 个答案:

答案 0 :(得分:1)

您仍未将控制器 getWheather方法绑定到任何函数,以便以后在视图中使用。

$scope.getWheather = getWheather;

然后你在getWheather方法上调用promise

function getWheather(city){
    wheatherService.getWheather(city).success(function(data){
        $scope.wheatherData = data;
        console.log($scope.wheatherData);
  });
}

在您看来ng-change应该将城市作为参数传递

ng-change="getWheather(city)"

答案 1 :(得分:0)

city 对象传递给函数。

&#xA;&#xA;
  ng-change =“getWheather(city)”&#xA; < /代码> 
&#XA;

答案 2 :(得分:0)

请记住,在视图中,您应该从控制器调用这些功能,控制器应该是与工厂通信的那个。

但是,要尝试回答你的问题,如果你将城市传递给getWheather,那么它将会被解决,因为你不接受你的getWheather函数中的任何参数。

var getWheather = function(){...应为var getWheather = function(city){...

然后在工厂你应该尝试这样的事情。

var url ="https://api.forecast.io/forecast/api_key/"+ city.latit +","+ city.longit +"?callback=JSON_CALLBACK";

希望这适合你= D!