我正在尝试使用修改来实现他们的AuthInterceptor,该修改处理具有多种不同类型错误的状态代码。这是我的代码:
angular.module('mobileDashboardApp')
.factory('AuthInterceptor', function ($rootScope, $q, AuthEvents) {
return {
responseError: function (response) {
$rootScope.$broadcast({
400: AuthEvents.notAuthorized,
401: if(response.header.messages === 'Your Session has timed out. Please login again.') {AuthEvents.sessionTimeout} else {AuthEvents.notAuthenticated},
500: AuthEvents.serverError,
503: AuthEvents.serviceError
}[response.status], response);
return $q.reject(response);
}
};
});
问题在于401 if语句。有谁知道如何解决这个问题?
答案 0 :(得分:1)
应该是
401: response.header.messages === 'Your Session has timed out. Please login again.' ? AuthEvents.sessionTimeout : AuthEvents.notAuthenticated,
答案 1 :(得分:0)
$rootScope.$broadcast
有两个参数的内容
第一个参数是一个带有AngularJS事件名称的文本字符串。第二个和后续参数作为处理函数的参数发送给侦听器。
$rootscope.$broadcast("eventName", { code: 404, name: "page not found"});
$scope.$on('eventName', function eventHandler (e) {
console.log("got eventName");
console.log(e.code);
console.log(e.name);
});
有关详细信息,请参阅AngularJS $rootscope.scope API Reference -- $broadcast
在我的示例中,例如错误代码为400的事件的名称是什么?
在您的示例中,如果您使用了Techniques for authentication in AngularJS applications
中的常量.constant('AuthEvents', {
loginSuccess: 'auth-login-success',
loginFailed: 'auth-login-failed',
logoutSuccess: 'auth-logout-success',
sessionTimeout: 'auth-session-timeout',
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
})
您的代码评估为:
{
400: AuthEvents.notAuthorized,
401: (response.header.messages
=== 'Your Session has timed out. Please login again.') ?
AuthEvents.sessionTimeout : AuthEvents.notAuthenticated,
500: AuthEvents.serverError,
503: AuthEvents.serviceError
}[400] == 'auth-not-authorized'