我有一个看起来像(Manufacturer -> Vehicle Type -> Vehicle Model -> Vehicle Submodel)
的实体层次结构。每个制造商都有多种车型,每种车型都有多种型号,每种车型都有多个子模型。
我需要检索给定制造商和类型的车辆模型列表,然后针对每个模型检索其所有子模型(getSubmodels
)。一旦他们全部被取出,我将它们放入JSON对象中。我试图使用Angular的$q
模块来确保在继续执行之前已经检索到所有子模型 - 我需要在我继续前进并渲染之前解决所有的承诺。页面组件。
快乐' path工作正常,但是如果其中一个子模型请求有错误,那么来自子模型函数的被拒绝的promise不会被$q.all().then
块捕获,因此整个getVehicleHierarchy promise不会被拒绝。
angular.module('uiApp.services.hierarchy', ['restangular'])
.service('VehicleHierarchy', function VehicleHierarchy($http, $q, Restangular) {
this.getVehicleHierarchy = function (manufacturerId, vehicleTypeId, vehicleModelId) {
var that = this;
var deferred = $q.defer();
var promise = deferred.promise;
var promises = [];
Restangular.configuration.baseUrl = urlBuilder.buildHierarchyServiceUrl() + '/vehicle-hierarchy';
Restangular.one('manufacturer', manufacturerId).one('type', vehicleTypeId).one('class', vehicleClassId).customGET('models')
.then(function (models) {
var result = {};
_.forEach(models.result, function (model) {
result[parseInt(model.id)] = model;
});
_.forEach(result, function (model) {
promises.push(that.getSubmodels(manufacturerId, vehicleTypeId, vehicleClassId, model.id));
});
$q.all(promises).then(function (results) {
var i = 0;
_.forEach(result, function (model) {
result[parseInt(model.id)].subModels = results[i++];
}, function (errors) {
deferred.reject(errorResponse);
});
deferred.resolve(result);
});
}, function(error) {
deferred.reject('error!');
});
return promise;
};
this.getSubmodels = function (manufacturerId, vehicleTypeId, vehicleClassId, modelId) {
var submodels = {};
var deferred = $q.defer();
Restangular.configuration.baseUrl = urlBuilder.buildHierarchyServiceUrl() + '/vehicle-hierarchy';
Restangular.one('manufacturer', brandId).one('type', vehicleTypeId).one('class', vehicleClassId).one('model', modelId)
.customGET('submodels').then(function (submodelResponse) {
_.forEach(subclassResponse.result, function (subModel) {
subclasses[parseInt(subModel.id)] = subModel;
});
deferred.resolve(subclasses);
}, function (error) {
deferred.reject('error'!);
});
return deferred.promise;
};
});
});
答案 0 :(得分:1)
您需要在$q.all
中为您的错误函数返回then
调用才能捕获它:
return $q.all(promises).then(function (results) {