在下面的代码中,我想处理错误:
我找不到正确的方法。
有什么想法吗?
谢谢,
Module.js
var app;
(function () {
app = angular.module("studentModule", []);
})()
Service.js
app.service('StudentService', function ($http) {
this.getAllStudent = function () {
return $http.get("http://myserver/api/Student/");
}
});
Controller.js
app.controller('studentController', function ($scope, StudentService) {
function GetAllRecords() {
var promiseGet = StudentService.getAllStudent();
promiseGet.then(function (pl) { $scope.Students = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
});
答案 0 :(得分:3)
与大多数问题一样,AngularJS中有许多不同的方法来处理来自AJAX请求的错误。最简单的是使用已经指出的HTTP拦截器。这可以处理身份验证和错误。
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$rootScope', '$q', function($rootScope, $q) {
return {
responseError: function(rejection) {
var deferred;
// If rejection is due to user not being authenticated
if ( rejection.status === 401 ) {
$rootScope.$broadcast('unauthenticated', rejection);
// Return a new promise since this error can be recovered
// from, like redirecting to login page. The rejection and
// and promise could potentially be stored to be re-run
// after user is authenticated.
deferred = $q.defer();
return deferred.promise;
}
$rootScope.$broadcast('serverError', rejection);
// Just reject since this probably isn't recoverable from
return $q.reject(rejection);
}
}
};
}]);
上述拦截器是使用匿名函数创建的,但工厂可用于处理一个或多个不同的拦截器。 AngularJS文档提供了关于如何编写不同文档的正确信息:https://docs.angularjs.org/api/ng/service/$http#interceptors
在拦截器到位的情况下,您现在只需要监听run方法或任何控制器中的广播事件。
app.run(['$rootScope', '$location', function($rootScope, $location) {
$rootScope.$on('unauthenticated', function(response) {
// Redirect to login page
$location.path('/login');
});
$rootScope.$on('serverError', function(response) {
// Show alert or something to give feedback to user that
// server error was encountered and they need to retry
// or just display this somewhere on the page
$rootScope.serverError = response.data.errorMessage;
});
}]);
在您看来:
<body ng-app="studentModule">
<div id="server_error" ng-if="!!serverError">{{serverError}}</div>
...rest of your page
</body>
与几乎所有AngularJS代码一样,大部分代码都可以抽象到不同的工厂和服务中,但这应该是一个很好的起点。