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

前端之家收集整理的这篇文章主要介绍了angularjs – 来自多个承诺的增量UI更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个AngularJS服务,用于根据索引(/ contacts)检索单个联系人(/ contacts /:id):
  1. app.service("CollectionService",function($http,$q) {
  2. this.fetch = function(collectionURL) {
  3. return $http.get(collectionURL).then(function(response) {
  4. var urls = response.data;
  5. var entities = urls.map(function(url) {
  6. return $http.get(url);
  7. });
  8. return $q.all(entities);
  9. }).then(function(responses) {
  10. return responses.map(function(response) {
  11. return response.data;
  12. });
  13. });
  14. };
  15. });
  16.  
  17. // used within the controller:
  18. CollectionService.fetch("/contacts").then(function(contacts) {
  19. $scope.contacts = contacts;
  20. });

结果以简单的列表(< li ng-repeat =“contact in contacts”> {{contact}}< / li>)显示.

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

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

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

HTML

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

调节器

  1. .controller("ContactController",["$scope","CollectionService",function (scope,service) {
  2. scope.contacts = [];
  3. scope.loading = true;
  4.  
  5. service.fetch("/contacts")
  6. .then(
  7. // All complete handler
  8. function () {
  9. console.log("Loaded all contacts");
  10. scope.loading = false;
  11. },// Error handler
  12. function () {
  13. scope.error = "Ruh roh";
  14. scope.loading = false;
  15. },// Incremental handler with .notify
  16. function (newContacts) {
  17. console.log("New contacts found");
  18. scope.contacts = scope.contacts.concat(newContacts);
  19. });
  20. }])

服务

  1. .service("CollectionService",["$q","$http",function (q,http) {
  2.  
  3. this.fetch = function (collectionUrl) {
  4.  
  5. var deferred = q.defer();
  6.  
  7. http.get(collectionUrl)
  8. .then(function (response) {
  9.  
  10. // Still map all your responses to an array of requests
  11. var allRequests = response.data.map(function (url) {
  12. return http.get(url)
  13. .then(function (innerResponse) {
  14. deferred.notify(innerResponse.data);
  15. });
  16. });
  17.  
  18. // I haven't here,but you could still pass all of your data to resolve().
  19. q.all(allRequests).then(function () {
  20. deferred.resolve();
  21. });
  22.  
  23. });
  24.  
  25. return deferred.promise;
  26.  
  27. }
  28.  
  29. }]);

您也可以按照您的看法和.reject()的承诺来处理错误

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

猜你在找的Angularjs相关文章