gpt4 book ai didi

angularjs - 在 Angular 中使用工厂时如何处理 $http 错误

转载 作者:行者123 更新时间:2023-12-02 20:31:59 25 4
gpt4 key购买 nike

我有一个如下所示的 Controller 和工厂,可以轻松处理成功。但是我如何处理错误?

Controller

app.controller("draftsCtrl", ["$scope", "DashboardFactory", function ($scope, DashboardFactory) {
DashboardFactory.drafts(function (successCallback) {
$scope.rooms listings= successCallback;
});
}]);

工厂

app.factory('DashboardFactory', function ($http) {
var DashboardFactory = {};

DashboardFactory.active_listings = function (successCallback) {
$http.get('active.json').success(successCallback);
}

DashboardFactory.inactive_listings = function (successCallback) {
$http.get('inactive.json').success(successCallback);
}

DashboardFactory.drafts = function (successCallback) {
$http.get('drafts.json').success(successCallback);
}
return DashboardFactory;
});

最佳答案

与其传递回调,不如选择正确的 Promise 工作流程。为此,使您的服务方法返回 promise objects :

app.factory('DashboardFactory', function ($http) {
var DashboardFactory = {};

DashboardFactory.active_listings = function () {
return $http.get('active.json');
}

DashboardFactory.inactive_listings = function () {
return $http.get('inactive.json');
}

DashboardFactory.drafts = function () {
return $http.get('drafts.json');
}

return DashboardFactory;
});

然后使用 Promise API 来处理成功(then 回调)和错误(catch):

app.controller("draftsCtrl", ["$scope", "DashboardFactory", function ($scope, DashboardFactory) {
DashboardFactory.drafts().then(function (response) {
$scope.rooms_listings = response.data;
})
.catch(function() {
console.log('Error ocurred');
});
}]);

关于angularjs - 在 Angular 中使用工厂时如何处理 $http 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36669012/

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