【问题标题】:API call inside for loop in angular角度的for循环内部的API调用
【发布时间】:2015-02-10 22:09:08
【问题描述】:

我正在尝试创建一个 Ionic 应用程序,为此我必须在 for 循环中发出一些 HTTP GET 请求,但似乎 angular 不会等待显示之前的数据。

这是我正在使用的代码。

$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 中显示,但是当我尝试使用第二个获取请求将附加数据添加到原始数据时,没有创建任何内容,或者有时只创建最后一个显示每个值。

【问题讨论】:

标签: angularjs rest ionic-framework ionic


【解决方案1】:

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

$http.get 发布请求,但直到 for 循环完成很长时间后才得到响应。因此,promise 成功回调中的$scope.threadPostNumber 将在分配后设置:

$scope.threadObj.count = $scope.threadPostNumber

所以这个任务实际上是没有用的。

为了修复,使用尾递归或Promise objects 为了使呼叫连续。

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

$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 (see the MDN page)、thread 和i 的作用域是函数,所以对于函数的生命周期以及它调用或创建的任何函数(如承诺成功回调) 、thread 和 i 将保留传递给函数的值。这可确保无论 HTTP 请求以何种顺序返回,您都将在正确的线程上设置 count。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    相关资源
    最近更新 更多