角度内的for循环的API调用 [英] API call inside for loop in angular

查看:118
本文介绍了角度内的for循环的API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 Ionic 应用,为此,我必须在for循环内发出一些 HTTP GET 请求,但看来angular并没有等待显示数据之前.

I'm trying to create an Ionic app and for this I have to make some HTTP GET request inside a for loop but it appears that angular does not wait for the data before showing them.

这是我正在使用的代码.

Here is a code I'm using.

$http.get(ApiUrl.get() + '/Threads' + '?access_token=' + $scope.userToken + filterString + "&filter[order]=created%20desc")
.success(function(data, status, headers, config) {

    var i=0;

    for(thread in data)
    {
        $scope.threadObj = data[i];
        var threadId = $scope.threadObj.id;
        $scope.threadPostNumber;

        //On récupére chaque nombre de post
        $http.get(ApiUrl.get() + '/Threads/' + threadId + '/posts/count' + '?access_token=' + $scope.userToken)
            .success(function(data, status, headers, config) {
                $scope.threadPostNumber = data.count;
            })
            .error(function(data, status, headers, config) {
                alert("Connection error, please try again.");
                $location.path("/app/carte");
            });

        $scope.threadObj.count = $scope.threadPostNumber;
        $scope.threads[i] = $scope.threadObj;

        i++;
    }
})
.error(function(data, status, headers, config) {
    alert("Connection error, please try again.");
    $location.path("/app/carte");
});

第一个 HTTP 获取已完成,数据可以在foreach中显示,但是当我尝试通过第二个get请求将原始数据添加到原始数据中时,则什么也没有创建,有时仅创建了最后一个每显示一个值.

The first HTTP get is done and the data can be show within the foreach but when I try to add additionnal data to the original ones with a second get request nothing is created or sometimes only the last value is shown for every one.

推荐答案

问题源于API调用是异步的,并且比for循环要慢得多.

The problem stems from the API call being asynchronous, and much slower than the for loop.

$http.get发布请求,但是直到for循环完成很长时间之后,它才获得响应.因此,将在答应成功回调中设置$scope.threadPostNumber:

The $http.get posts the request, but it doesn't get the response until long after the for loop completes. As a consequence $scope.threadPostNumber inside the promise success callback is going to be set after it is assigned in:

$scope.threadObj.count = $scope.threadPostNumber

因此,这种分配实际上是没有用的.

So effectively this assignment is useless.

为了解决问题,请使用尾部递归或承诺对象 为了使通话连续进行.

In order to fix, use tail recursion or Promise objects in order to make the calls consecutive.

您还可以适当地确定当前线程对象的范围,以便在Promise成功时可以修改正确的线程:

You can also properly scope the current thread object so that when the promise succeeds you will be modifying the correct thread:

$http.get(ApiUrl.get() + '/Threads' + '?access_token=' + $scope.userToken + filterString + "&filter[order]=created%20desc")
.success(function(data, status, headers, config) {

    data.forEach(function(thread, i) {

        $scope.threads[i] = thread;

        var threadId = thread.id;

        $http.get(ApiUrl.get() + '/Threads/' + threadId + '/posts/count?access_token=' + $scope.userToken)
            .success(function(data, status, headers, config) {

                $scope.threads[i].count = data.count;
            })
            .error(function(data, status, headers, config) {

                alert('Connetion error, please try again.');
                $location.path('/app/carte');
            });
    });
})
.error(function(data, status, headers, config) {
    alert("Connection error, please try again.");
    $location.path("/app/carte");
});

因为这使用了forEach(请参阅MDN页面),threadi的作用域范围,因此在该函数及其调用或创建的任何函数(例如promise成功回调),threadi将保留传递给函数的值.这样可以确保无论HTTP请求返回的顺序如何,您都将在适当的线程上设置count.

Because this uses forEach (see the MDN page), thread and i are scoped to the function, so for the lifetime of that function and any functions that it calls or creates (like the promise success callback), thread and i will remain the value passed into the function. This ensures that no matter what order the HTTP requests return in, you'll be setting count on the proper thread.

这篇关于角度内的for循环的API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆