AnC*_*AnC 13 promise angularjs
我有一个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;
});
Run Code Online (Sandbox Code Playgroud)
结果显示在一个简单的列表中(<li ng-repeat="contact in contacts">{{ contact }}</li>
).
但是,由于使用$q.all
,该列表在收到最后(最慢)响应之前不会更新.当收到单个联系人时,如何从批量更新切换到增量更新?
您可以将联系人列表传递给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);
Run Code Online (Sandbox Code Playgroud)
你可以使用自己的承诺要恢复,然后挂接到承诺的通知给你的整体负载的最新进展,并仍然使用$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>
Run Code Online (Sandbox Code Playgroud)
调节器
.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);
});
}])
Run Code Online (Sandbox Code Playgroud)
服务
.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;
}
}]);
Run Code Online (Sandbox Code Playgroud)
您也可以根据自己的意愿和.reject()
承诺处理错误:
http://docs.angularjs.org/api/ng/service/$q
归档时间: |
|
查看次数: |
1519 次 |
最近记录: |