【问题标题】:Show spinner on multiple $http calls angularJs在多个 $http 调用 angularJs 上显示微调器
【发布时间】:2023-04-05 01:19:01
【问题描述】:

这就是交易。

我在进行 $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)
});

两个控制器可能同时调用服务,可能会得到不同的响应。

【问题讨论】:

    标签: javascript http angularjs spinner


    【解决方案1】:

    Angular 中的所有 $http 调用都返回一个承诺。

    $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;
        });
      };
    });
    

    【讨论】:

    • 如果 $http 调用来自不同的控制器,有没有办法做到这一点?
    • 是的,您必须创建工厂或服务来为您管理它。但这做出了某些假设,例如电话总是同时进行的。如果它们是在不同的时间制作并收到不同的结果,那么拥有一个“全局”加载状态可能是奇怪的用户体验。
    • 谢谢,对我帮助很大。
    【解决方案2】:

    使用初始化为您正在进行的调用次数的变量。在 AJAX 调用的每个回调中,调用一个递减该变量值的函数,如果它为零,则移除微调器。

    num_calls = 3;
    
    function considerRemoveSpinner() {
        if (--window.num_calls == 0)
        {
            removeSpinner();
        }
    
    } 
    
    $http.get("url").success(
        function() {
            /* regular handler */
            considerRemoveSpinner();
       }
    );
    
    /* other ajax calls */
    

    【讨论】:

    • 这是有道理的,但我希望 Angular 已经为此提供了一些东西。
    【解决方案3】:

    您可以通过使用拦截器并在每个 API 的标头中传递一个标志来做到这一点。您需要做什么。在每个 $http 调用中添加一个参数。

    通过使用属性config.headers.{{Parameter}}在拦截器Request方法中捕获它。在此标志的基础上广播一个显示等待图像的事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多