【问题标题】:How to Handle multiple Ajax call calling same function?如何处理调用同一函数的多个 Ajax 调用?
【发布时间】:2017-03-11 08:30:25
【问题描述】:

嗨,页面上有 4 个指令,所有指令都需要用户列表。 用户列表存储在需要 hhtp 请求的数据库中。 由于页面上同时存在 4 个指令,因此已将 4 个不同的 ajax 调用发送到服务器以获得类似的响应。

然后响应被缓存。

可以做什么,所有 4 个指令都接收到它的用户列表,并且只有一个 ajax 被发送到服务器。

指令内的代码(self is this)(ajaxCallService 是服务)

ajaxCallService.getUser(function(response) {
                self.users = response;
                //Next operations
});

ajaxCallService 服务

Variable
var userList = []

Method
if (!userList.length) {
          $http.post({
                url: #,
                data:#
            })
            .then(
                function(response) {
                        userList = response.allMembers;
                        callback && callback(userList);
                }
            );
        }else{
            callback && callback(userList);
        }

如何防止 4 个 ajax 调用,只进行 1 个调用,让其他 3 个等待响应并返回响应?

【问题讨论】:

  • 使用角度承诺。
  • 在前一个的回调中调用每个ajax函数。

标签: javascript angularjs angularjs-directive angularjs-service angular-http


【解决方案1】:

您可以为此使用 Promise,以查看它是否已经在运行。因为服务在 Angular 中是单例的,所以你知道它始终是一个共享实例:

var userList = [];
var promise;

function getUser() {
    // inject the $q service
    var deferred = $q.defer();

    if (userList.length) {
        // already got data, immediately resolve that one
        deferred.resolve(userList);
    }

    if (promise) {
        // a promise is already working on it, return this one
        return promise;
    } else {
        $http.post(...).success(function(response) {
            userList = response;
            deferred.resolve(response);
        });
    }

    // if this point is reached, this is the first call
    // assign the promise so other calls can know this one is working on it
    promise = deferred.promise;
    return promise;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多