gpt4 book ai didi

angularjs - 来自多个 promise 的增量 UI 更新

转载 作者:行者123 更新时间:2023-12-03 23:47:50 24 4
gpt4 key购买 nike

我有一个 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 ,直到收到最后一个(最慢的)响应,该列表才会更新。当收到个人联系人时,如何从批量更新切换到增量更新?

最佳答案

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

fiddle :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
.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() promise :

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

关于angularjs - 来自多个 promise 的增量 UI 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21969708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com