在Angular中放置事件监听的位置

时间:2016-08-11 08:43:58

标签: javascript angularjs

在我目前基于模块/组件的架构中,我从API调用中拦截了所有responseErrors,如果我遇到401 Unauthorized,我就会重定向到注销页面。

我目前的代码是:

angular
    .module('core')
    .factory('authHTTPInterceptor', authHTTPInterceptor)
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.interceptors.push('authHTTPInterceptor');
    }]);

function authHTTPInterceptor($rootScope) {
    return {
        'responseError': function (response) {
            console.log(response.status);
            if (response.status == 401)
                redirectToLogout();
            return response;
        }
    };

    function redirectToLogout() {
        window.location.href = 'logout.html';
    }
}

我想将redirectToLogout逻辑移动到另一个实体,并发出unathorized事件以保持逻辑分离并对其进行单元测试。

我的问题是:什么角度实体应该是听这种事件的人。这个模块中的控制器,或者放在像<redirectListener></redirectListener>这样的html代码中的组件,还是别的东西?或者我应该创建redirector服务并注入此处?对此最好的做法是什么?

1 个答案:

答案 0 :(得分:1)

这就是我们所遵循的。

您可以为其定义一条路线,而不是使用js将网址重定向到logout.html。

.state('logout', {
    url: '/logout',
    controller: 'LogoutController',
    templateUrl: "/logout.html",
    access: 0
})

在logoutController中,您可以添加代码。

通过这种方式,从任何模块,如果有人未经授权,那么它将重定向到特定的URL,并且在注销逻辑中将在一个控制器。