javascript - 在多个 $http 调用上显示微调器

标签 javascript http angularjs spinner

这就是交易。

我在进行 $http 调用时要显示微调器,但这里的问题是我有多个调用,所以我在此处找到的示例没有帮助。

有人对此有解决方案吗?

一种方法来堆叠调用,以便微调器保持到最后一个调用结束?我希望表达我的观点。

我正在做这个。

angular.module('moduleName', []).
factory.("SomeService", function () {
    return:{
        getResources(params) {
        /* do the $http call */
        }
    }
}).
controller("SomeCtrl", function (SomeService) {
    SomeService.getResources(params)
}).
controller("OtherCtrl", function (SomeService) {
    SomeService.getResources(params)
});

两个 Controller 可能会同时调用该服务,并且可能会得到不同的响应。

最佳答案

Angular 中的所有 $http 调用都会返回一个 promise。

$q 服务没有 Q 的所有功能。它所基于的库,但是如果您查看 docs ,它确实有一个 all 方法,可用于为您提供所需的功能。

以下是您可以如何使用它:

app.controller('HttpController', function($http, $q) {

  // A hypothetical submit function
  $scope.submit = function() {
    // Set a loading variable for use in the view (to show the spinner)
    $scope.loading = true;

    var call1 = $http.get(/* ... */);
    var call2 = $http.get(/* ... */);
    var call3 = $http.get(/* ... */);

    $q.all([call1, call2, call3]).then(function(responses) {
      // responses will be an array of values the individual
      // promises were resolved to. For this case, we don't 
      // need it, since we only care that they all resolved
      // successfully.

      $scope.loading = false;
    }, function(errorValue) {
      // If any of the promises is rejected, the error callback 
      // will be resolved with that rejection value, kind of like
      // an early exit. We want to mark the loading variable
      // as false here too, and do something with the error.

      $scope.loading = false;
    });
  };
});

关于javascript - 在多个 $http 调用上显示微调器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16778140/

相关文章:

javascript - 在 ionic 应用程序中共享 PDF

javascript - 如何检查没有链接的节点的 d3 js 力图并将其删除?

rest - 当部分批量更新失败时,我应该返回什么状态代码?

Spring Security (3.2.5) HTTP POST 认证后不转发到原始请求

javascript - Angularjs Jasmine 测试 : Making api call with $backend

javascript - 在 Bootstrap 日期时间选择器中更改 meridiem (am pm) 的文本

javascript - 如何在 Angular2 的 ngFor span 中添加/删除类?

c++ - 需要在 C++ 中使用 Qt 4.7 创建 http 网络服务器

javascript - mongodb如何获取当前登录用户

javascript - ng-repeat 中的下拉菜单无法正常工作