如果连接到我的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;
});
答案 0 :(得分:7)
我想这就是你要找的东西:
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可以到达,则以外部承诺的分辨率从中返回数据。否则,您将根据外部承诺的解决方案从其他服务返回您的硬编码数据。
答案 1 :(得分:2)
没有catch块,使用常规错误回调函数:
API.query()
.$promise
.then(function(data) {
isEmpty = (data.length === 0);
if (!isEmpty) {
days = data;
},
function(error) { // removed catch here
console.log("rejected " + JSON.stringify(error));
var data = null;
days = dataFactory.daysOfWeek;
console.log(days.length); // returns 5
...
请参阅docs:
然后(successCallback, errorCallback ,notifyCallback) - 无论何时或将要解析或拒绝承诺,只要结果可用,就会异步调用其中一个成功或错误回调。使用单个参数调用回调:结果或拒绝原因。此外,在解决或拒绝承诺之前,可以将通知回调调用零次或多次以提供进度指示。