我有一些Web API返回數據。 現在我想根據這些數據創建一個自定義對象。 問題是這些http調用是依賴的。 下面是代碼,你可以看到,在getLabMainAndLinesCombined() 有封裝在4個HTTP調用:如何同步HTTP調用並在最後返回承諾?
- contactsService.getContactPersonsIdNameList()
- getLabMainsIdAppIdList()
- getAllLabLines()
- getAllLabMains()
並且最後還有就是生成適合的應用程序,'粘貼'它。
var generateProperMappings = function (companiesIdName, contactPersonsIdName, labMainsIdAppId, labMains, labLines) {
var result = [];
var i = 0;
while (i < labMains.length) {
var labMain = labMains[i];
var workAppId = labMainsIdAppId.filter(options => options.id === labMain.id)[0].appId;
var companyName = companiesIdName.filter(options => options.id === labMain.companyId)[0].name;
var contactPersonName = contactPersonsIdName.filter(options => options.id === labMain.contactPersonId)[0].fullName;
var associatedLabLines = labLines.filter(options => options.assignedToWork === labMain.id);
var viewDetails = {
work: { id: labMain.id, appId: workAppId },
company: { id: labMain.companyId, name: companyName },
contactPerson: { id: labMain.contactPersonId, fullName: contactPersonName },
workDetails: { created: labMain.dateCreated },
labLinesAssociated: associatedLabLines
}
result.push(viewDetails);
i++;
};
return result;
};
var getLabMainAndLinesCombined = function() {
var deferred = $q.defer();
console.log("Generating view of mains and lines combined");
var companiesIdName = [];
var contactPersonsIdName = [];
var labMainsIdAppId = [];
var labLines = [];
var labMains = [];
var result = [];
contactsService.getCompaniesIdNameList().then(data => {
angular.copy(data, companiesIdName);
contactsService.getContactPersonsIdNameList().then(data => {
angular.copy(data, contactPersonsIdName);
getLabMainsIdAppIdList().then(data => {
angular.copy(data, labMainsIdAppId);
getAllLabLines().then(data => {
angular.copy(data, labLines);
getAllLabMains().then(data => {
angular.copy(data, labMains);
result.push(generateProperMappings(companiesIdName, contactPersonsIdName, labMainsIdAppId, labMains, labLines));
});
});
});
});
});
deferred.resolve(result);
return deferred.promise;
};
的問題是,這一功能(服務功能)是由控制器進行調用,但真正產生之前,它返回的結果數據... 這裏是電話:
var onLabLinesReceived = function (data) {
console.log(data);
angular.copy(data, vm.labLines);
}
labService.getLabMainAndLinesCombined().then(onLabLinesReceived, onError).finally(function() { vm.isBusy -= 1 });
在調試@瀏覽器,它看起來像這樣:
labService.js:電源的53視圖生成和線結合contactsService.js:27個讓所有公司的ID名單labLinesTableController.js:35] < - 問題contactsService。 JS:36個獲得所有通訊錄ID名稱列表labService.js:15個讓所有實驗室電源labService.js:7個讓所有實驗室線labService.js:15個讓所有實驗室電源
有獨立的電話。使用$ q.all() –