我有一个AngularJS服务,用于根据索引(/ contacts)检索单个联系人(/ contacts /:id):
- 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,该列表在接收到最后(最慢)的响应之前不会被更新.当接收到个人联系人时,如何从此批量更新切换到增量更新?
您可以使用自己的承诺返回,然后挂接到承诺的通知,以提供整体加载进度的更新,并仍然使用$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()的承诺来处理错误: