【问题标题】:Display data same time after nested http.request AngularJS嵌套 http.request AngularJS 后同时显示数据
【发布时间】:2018-03-13 11:44:19
【问题描述】:

我有一个关于多个像这样嵌套的 http 请求的问题:

  $http({
    method: 'jsonp',
    url: 'URL1',
  }).then(function (response) {
    // Response result 1
    // nested http request --> after first http success
    $http({
       method: 'jsonp',
       url: 'URL2'
    }).then(function (response) {
      // Response result 2

    }, function Error(response) {
      $scope.users = response.statusText;

    }).finally(function () {
      $scope.loading = false;

    });
  });
};

有没有办法同时在视图上显示两个结果?当我添加$scope.data.length 以确定显示按钮if length is > 1 时,该按钮位于任何数据之前。我想同时显示两个成功的数据。这可能吗?

我已经阅读了有关 $q 的信息,但这是否可以在这里工作并在两个结果数据可用的同时渲染视图?

PS:我知道在控制器中添加http 请求是不好的做法,但这只是为了测试。

【问题讨论】:

    标签: javascript angularjs http model-view-controller


    【解决方案1】:

    正如你所说,你必须像这样使用 $q :

    $q.all([$http({ method: 'jsonp', url: 'URL1'}).$promise, $http({ method: 'jsonp', url: 'URL2'}).$promise]).then(callBackSuccess, callBackError);
    
    function callBackSuccess(results){
    var firstResult = results[0];
    // do what do you want from firstResult
    var secondResult = results[1];
    // do what do you want from secondResult
    }

    【讨论】:

      【解决方案2】:

      我建议使用承诺链。也使用 catch 方法,它应该提高代码的可读性。

      $http({ method: 'jsonp', url: 'URL1'})
         .then(function (firstResult) {
           //save firstResult
           return $http({ method: 'jsonp', url: 'URL2'})
         })
         // this then will be called only if first one succeeds
         .then(function (secondResult) {
          //save secondResult - display data if this is available
         })
         .catch(function Error(response) {
            // catch errors form both requests
            $scope.users = response.statusText;
         })
         .finally(function () {
            $scope.loading = false;
         })
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        • 2016-07-24
        相关资源
        最近更新 更多