[英]Angular promises using multiple http requests
我之前閱讀過一些關於角度承諾的論壇帖子,但無法在我的實例中正常工作。 我正在使用nodejs / locomotive作為后端,而Angular則使用前端。
我在控制器中有以下代碼,基本上我想使用slides.path的路徑,如何使用promises來做到這一點? 任何幫助將不勝感激。
function ProductCtrl($scope, $http, $q) {
$scope.events = [];
$scope.times = [];
var html = [];
var chapters = [];
var path;
//var paPromise = $q.defer();
$http({
url: '/show',
method: 'GET',
params: { eventid:$scope.$routeParams.eventid}
}).success(function(response, code) {
$scope.events = response;
angular.forEach($scope.events.slides, function(slide) {
$http({
url: '/upload',
method: 'GET',
params: {uploadid: slide.upload.toString()}
}).success(function(response, code) {
return "http://www.example.com/"+response.path;
},path);
slide.path = path;
chapters.push(slide);
});
});
}
您可以使用$ q.all來完成此多承諾問題。 像這樣:
function ProductCtrl($scope, $http, $q) {
$scope.events = [];
$scope.times = [];
var html = [];
var path;
function fetchChapter() {
var chapters = [];
var httpPromise = $http({
url: '/show',
method: 'GET',
params: {
eventid: $scope.$routeParams.eventid
}
});
//Return the value http Promise
return httpPromise.then(function (response) {
$scope.events = response;
var promises = [];
angular.forEach($scope.events.slides, function (slide) {
var inPromise = $http({
url: '/upload',
method: 'GET',
params: {
uploadid: slide.upload.toString()
}
}).then(function (response, code) {
//each promise makes sure, that he pushes the data into the chapters
slide.path = "http://www.example.com/" + response.path;
chapters.push(slide);
});
//Push the promise into an array
promises.push(inPromise);
});
//return the promise from the $q.all, that makes sure, that all pushed promises are ready and return the chapters.
return $q.all(promises).then(function () {
return chapters;
});
});
}
fetchChapter().then(function(chapters){
//populate here
});
}
httpPromise將返回$ q.all的承諾。
編輯:如何獲取數據,然后包裝一個函數,我用fetchChapter
,並將一個函數傳遞到, then
將您需要的值作為參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.