angularjs - 在 Angular 中,通过异步调用持久化数据的最佳方式是什么?

标签 angularjs http asynchronous

我有一个带有 for 循环的 Controller ,它使 HEAD 请求一组 URL 来检查文件是否存在。当我从 HEAD 请求获得响应时,我需要该请求所基于的数组中的索引号。

var allFiles = [], files = [];
allFiles.push({"url":"http://www.example.com/foo","source":"source1"});
allFiles.push({"url":"http://www.example.com/bar","source":"home"});
allFiles.push({"url":"http://www.example.com/wtf","source":"outer space"});

for(var i=0,len=allFiles.length;i<len;i++) {
    $http.head(allFiles[i].url).then(function(response) {
        files.push(allFiles[VALUE_OF_i_AT_TIME_OF_REQUEST]);
   }
}

编辑:
因为它是一个异步调用,所以我不能用 i 代替 VALUE_OF_i_AT_TIME_OF_REQUEST。这样做会导致 i 始终等于 len-1

我想我可以将索引号作为数据与请求一起发送,并从响应中检索它,但出于某种原因,这对我来说似乎是 hack-ish。

有没有更好的办法?

最佳答案

你可以用一个函数闭包来做到这一点

for (var i = 0, len = allFiles.length; i < len; i++) {
    function sendRequest(index) {
        $http.head(allFiles[index].url).then(function (response) {
            files.push(allFiles[index]);
        });
    }

    sendRequest(i);
}

关于angularjs - 在 Angular 中,通过异步调用持久化数据的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29677313/

相关文章:

javascript - 正则表达式/ng 模式接受某些字符

javascript - AngularJS $timeout 的工作方式不同

javascript - AngularJS 自定义提供程序导致 "Unknown provider"异常

azure - 映射 JSON 列 Azure 数据工厂

javascript - Javascript async 和 await 是否等同于多线程?

asynchronous - 为什么 Spring-Data-JPA 异步不起作用?

javascript - 如何使用 Angular、Spring MVC 显示 JSON 数据?

http - 如何处理同名的多个cookie?

angular - 如何用switchMap取消http请求?

c# - 需要帮助解决有关异步服务器套接字的一些逻辑错误