来自多个承诺的增量UI更新

时间:2014-02-23 14:45:47

标签: angularjs promise

我有一个AngularJS服务,用于根据索引(/contacts/:id)检索单个联系人(/contacts):

app.service("CollectionService", function($http, $q) {
    this.fetch = function(collectionURL) {
        return $http.get(collectionURL).then(function(response) {
            var urls = response.data;
            var entities = urls.map(function(url) {
                return $http.get(url);
            });
            return $q.all(entities);
        }).then(function(responses) {
            return responses.map(function(response) {
                return response.data;
            });
        });
    };
});

// used within the controller:
CollectionService.fetch("/contacts").then(function(contacts) {
    $scope.contacts = contacts;
});

结果显示在一个简单的列表中(<li ng-repeat="contact in contacts">{{ contact }}</li>)。

但是,由于使用$q.all,该列表在收到最后一个(最慢)响应之前不会更新。当收到单个联系人时,如何从批量更新切换到增量更新?

5 个答案:

答案 0 :(得分:6)

你可以将联系人列表传递给fetch()并让它弹出列表。

app.service("CollectionService", function($http, $q) {
    this.fetch = function(collectionURL, resultList) {
        $http.get(collectionURL).then(function(response) {
            var urls = response.data;
            urls.forEach(function(url) {
                $http.get(url).then(function(response) {
                    resultList.push(response.data);
                });
            });
        };
    };
});

// used within the controller:
$scope.contacts = [];
CollectionService.fetch("/contacts", $scope.contacts);

答案 1 :(得分:5)

您可以使用自己的承诺返回,然后挂钩到承诺的通知,以便为您提供有关整体加载进度的更新,并仍然使用$q.all来确定何时完成。它基本上就是你现在拥有的处理和使用自定义承诺的方式略有不同。

小提琴:http://jsfiddle.net/U4XPU/1/

HTML

<div class="wrapper" ng-app="stackExample">
    <div class="loading" ng-show="loading">Loading</div>
    <div class="contacts" ng-controller="ContactController">
        <div class="contact" ng-repeat="contact in contacts">    {{contact.name}} - {{contact.dob}}</div>
    </div>
</div> 

控制器

.controller("ContactController", ["$scope", "CollectionService", function (scope, service) {
    scope.contacts = [];
    scope.loading = true;

    service.fetch("/contacts")
        .then(
    // All complete handler
    function () {
        console.log("Loaded all contacts");
        scope.loading = false;
    },
    // Error handler
    function () {
        scope.error = "Ruh roh";
        scope.loading = false;
    },
    // Incremental handler with .notify
    function (newContacts) {
        console.log("New contacts found");
        scope.contacts = scope.contacts.concat(newContacts);
    });
}])

服务

.service("CollectionService", ["$q", "$http", function (q, http) {

    this.fetch = function (collectionUrl) {

        var deferred = q.defer();

        http.get(collectionUrl)
        .then(function (response) {

            // Still map all your responses to an array of requests
            var allRequests = response.data.map(function (url) {
                return http.get(url)
                    .then(function (innerResponse) {
                        deferred.notify(innerResponse.data);
                    });
            });

            // I haven't here, but you could still pass all of your data to resolve().
            q.all(allRequests).then(function () {
                deferred.resolve();
            });

        });

        return deferred.promise;

    }

}]);

您也可以根据需要处理错误并.reject()承诺:

http://docs.angularjs.org/api/ng/service/$q

答案 2 :(得分:1)

我想出了一个解决方法,允许单独为每个响应调用onResponse回调:

var entities = urls.map(function(url) {
    var request = $http.get(url);
    if(onResponse) {
        request.then(function(response) {
            onResponse(response.data);
        });
    }
    return response; // this still allows for `$q.all` to handle completion
});

但是,我并不热衷于API混合回调和承诺 - 所以我仍然很好奇是否有更优雅的解决方案。

答案 3 :(得分:0)

如果您只是返回一个空列表并让服务在每个已提交的请求上添加条目,它可能会起作用:

app.service("CollectionService", function($http, $q) {
    this.fetch = function(collectionURL) {
        var list = [];
        $http.get(collectionURL).then(function(response) {
            var urls = response.data;
            urls.forEach(function(url) {
                $http.get(url).then(function(response) {
                    list.push(response.data);
                });
            });
        };
        return list;
    };
});

$scope.contacts = CollectionService.fetch("/contacts");

答案 4 :(得分:0)

如果我理解正确,你需要一个应该

的解决方案
  • 在加载所有联系人之前开始显示联系人
  • 避免回调
  • 了解加载所有联系人的时间
  • 确保只有服务知道数据结构
  • 允许在控制器中处理错误

app.service("CollectionService", function($http, $q) {
    this.fetch = function(collectionURL) {
        return $http.get(collectionURL).then(function(response) {
            var urls = response.data;
            var contactPromises = urls.map(function(url) {
                return $http.get(url).then(function(response) {
                    return $q.when(response.data);
                });
            });
            return $q.when(contactPromises);
        });
    };
});

// used within the controller:
$scope.contacts = [];
var addContact = function(contact) { $scope.contacts.push(contact); }; 

CollectionService.fetch("/contacts").then(function(contactPromises) {
    contactPromises.forEach(function(contactPromise){
        contactPromise.then(addContact);
    });
    return $q.all(contactPromise);        
}).then(function(){
   alert('All contacts loaded!');
}, function(){
   alert('Error!!');
});