【问题标题】:AngularJS multiples http.getAngularJS 倍数 http.get
【发布时间】:2014-08-25 23:15:22
【问题描述】:

大家好,我是 AngularJS 的新手,我在调用倍数 http.get 时遇到问题。 $scope.countries 正在从城市获取价值。发生了什么事? 怎么能调用多个http.get?

$scope.getInfo = function(){
    $scope.refreshing=true;
    //cities
    $http.get(baseUrl+'cities/GET_INFO/ALL').success(function(data) {            
        $scope.cities = data[0];
        $scope.cities.signal = $scope.getSignal(data[0].status);        
        $scope.refreshing=false;    
        alert('city');
    });      


    //countries
    $http.get(baseUrl+'countries/GET_INFO/ALL').success(function(data) {
        $scope.countries = data[0];            
        $scope.countries.signal = $scope.getSignal(data[0].status);
        $scope.refreshing=false;
        // alert('countries');
    });
}

我也试过:

$scope.getInfo2 = function(){
    $scope.refreshing=true;
    alert ('start');

    $scope.urlcities = $http.get(baseUrl+'cities/GET_INFO/ALL');
    $scope.urlcountries = $http.get(baseUrl+'cities/GET_INFO/ALL');

    $q.all([$scope.urlcities, $scope.urlcountries]).then(function(values) {
        alert('finish');             
        $scope.refreshing=false;
    });
}

但是这段代码出错了。非常感谢您的帮助!

【问题讨论】:

  • 如果你可以控制你的数据源,我认为你需要从不同的角度来看待这个问题。获取关系数据时不需要多个 http 请求,因为这些都可以从一个端点返回。
  • 每个响应的原始文本是什么?

标签: javascript angularjs http get


【解决方案1】:

卡洛斯,

AJAX 调用可能存在竞争条件。尝试使用 Promise 将它们链接在一起:

$scope.getInfo = function(){
    $scope.refreshing=true;
    //cities
    $http.get(baseUrl+'cities/GET_INFO/ALL').then(function(data) {            
      $scope.cities = data[0];
      $scope.cities.signal = $scope.getSignal(data[0].status);        
      $scope.refreshing=false;    
      alert('city');

      return $http.get(baseUrl+'countries/GET_INFO/ALL');
    }).then(function(data) {
      // countries
      $scope.countries = data[0];            
      $scope.countries.signal = $scope.getSignal(data[0].status);
      $scope.refreshing=false;
      // alert('countries');
    });
};

要了解更多信息,请观看截屏视频: https://egghead.io/lessons/angularjs-chained-promises

您还可以在此处了解有关 Promise 的更多信息: https://docs.angularjs.org/api/ng/service/$q

注意:

将数据准备、业务逻辑和计算从控制器移到服务中是一种最佳做法。考虑修改代码以将 AJAX 请求(使用 $http 服务)封装到服务中,然后将该服务注入用于将数据呈现给视图的控制器中。

【讨论】:

    【解决方案2】:

    您需要进行同步调用。 而在 Angular 世界中,它是使用 $q 或 promise 来实现的。

    关于http://haroldrv.com/2015/02/understanding-angularjs-q-service-and-promises/的好文章

    希望对你有帮助..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-30
      • 2014-09-12
      • 2019-12-02
      • 2016-03-29
      • 2018-02-03
      • 2013-04-11
      • 2014-05-03
      • 1970-01-01
      相关资源
      最近更新 更多