javascript – angularjs处理$resource $promise错误
作者:互联网
如果连接到我的API时出错,有人可以帮我弄清楚如何在我的AngularJS工厂中返回硬编码数据.我的硬编码数据位于另一个名为“dataFactory”的工厂中.感谢您的帮助.
service.factory("ScheduleFactory", ['$http', '$resource', '$q', 'dataFactory', function($http, $resource, $q, dataFactory) {
var objFactory = {};
objFactory.getDaysOfWeek = function(includeWeekends) {
var days = [];
var API = $resource(restURL + '/daysOfWeek/');
API.query()
.$promise
.then(function(data) {
isEmpty = (data.length === 0);
if (!isEmpty) {
days = data;
};
})
.catch(function(error) {
console.log("rejected " + JSON.stringify(error));
var data = null;
days = dataFactory.daysOfWeek;
console.log(days.length); // returns 5
});
console.log("after promise " + days.length); // returns 'after promise 0'
return days;
};
我的dataFactory定义如下:
dataApp.factory("dataFactory", function() {
objDataFactory = {};
objDataFactory.daysOfWeek = [
{ dayName: 'Monday'
, dayAbbrev: 'Mon'
, index: 1
, isSelected: false
, isWeekday: true }
, { dayName: 'Tuesday'
, dayAbbrev: 'Tue'
, index: 2
, isSelected: false
, isWeekday: true }
, { dayName: 'Wednesday'
, dayAbbrev: 'Wed'
, index: 3
, isSelected: false
, isWeekday: true }
, { dayName: 'Thursday'
, dayAbbrev: 'Thu'
, index: 4
, isSelected: false
, isWeekday: true }
, { dayName: 'Friday'
, dayAbbrev: 'Fri'
, index: 5
, isSelected: false
, isWeekday: true }
];
return objDataFactory;
});
解决方法:
我想这就是你要找的东西:
service.factory("ScheduleFactory", ['$http', '$resource', '$q', 'dataFactory', function($http, $resource, $q, dataFactory) {
var objFactory = {};
objFactory.getDaysOfWeek = function(includeWeekends) {
var API = $resource(restURL + '/daysOfWeek/'), defObj = $q.defer();
var daysQuery = API.query();
daysQuery.$promise.then(function(data) {
//you can add anything else you want inside this function
defObj.resolve(data);
}, function(error) {
//you can add anything else you want inside this function
defObj.resolve(dataFactory.daysOfWeek);
});
return defObj.promise;
};
我已经跳过任何数据格式和分配细节,因为无论如何你都有可能改变它们.通过将API查询包装在额外的承诺中,您可以操纵返回的内容.如果您的API可以到达,则以外部承诺的分辨率从中返回数据.否则,您将根据外部承诺的解决方案从其他服务返回您的硬编码数据.
标签:angular-promise,javascript,angularjs,angular-resource 来源: https://codeday.me/bug/20190722/1506401.html