什么$ rootScope。$播放两个参数

时间:2016-01-06 17:18:05

标签: angularjs

我正在关注这篇文章:https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec#.rlvow9x66

我正在尝试使用修改来实现他们的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语句。有谁知道如何解决这个问题?

2 个答案:

答案 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

中的常量

AUTH EVENTS常量

.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'