gpt4 book ai didi

javascript - angularjs 处理 $resource $promise 错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:14:55 27 4
gpt4 key购买 nike

如果连接到我的 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;
};

我的数据工厂定义如下:

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 查询包装在一个额外的 promise 中,您可以获得操纵返回内容的能力。如果可以访问您的 API,您将在外部 promise 的解决方案中返回它的数据。否则,您将在解决外部 promise 时从其他服务返回硬编码数据。

关于javascript - angularjs 处理 $resource $promise 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070690/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com