简体   繁体   English

在Angular中将事件监听放在哪里

[英]Where to put event listening in Angular

In my current module/component-based architecture I'm intercepting all responseErrors from API calls, and if I come across 401 Unauthorized , I'm redirecting to the logout page. 在我当前的基于模块/组件的体系结构中,我拦截了API调用中的所有responseErrors ,并且如果遇到401 Unauthorized ,我将重定向至注销页面。

My current code is: 我当前的代码是:

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';
    }
}

I want to move redirectToLogout logic to another entity, and emit unathorized event in order to keep logic separated and unit test this properly. 我想将redirectToLogout逻辑移到另一个实体,并发出未unathorized事件,以保持逻辑分离并对此进行正确的单元测试。

My question is: what angular entity should be the one to listen for such event. 我的问题是:哪个角实体应该是侦听此类事件的对象。 Controller in this module, or component put in the html code like <redirectListener></redirectListener> , or something else? 这个模块中的控制器,还是放在<redirectListener></redirectListener>类的html代码中的组件,还是其他东西? Or should I just create redirector service and inject here? 还是应该只创建redirector服务并在此处注入? What's best practice for this? 最佳做法是什么?

This is what we follow. 这就是我们所遵循的。

Instead of redirecting url to logout.html using js, you can define one route for it. 无需使用js将url重定向到logout.html,而是可以为其定义一条路由。

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

And in logoutController, you can add your code. 在logoutController中,您可以添加代码。

by using this way, from any module if somebody is unauthorized then it will redirect to particular url and in logout logic will be at one controller. 通过这种方式,如果有人未经授权,则可以从任何模块从任何模块重定向到特定的url,注销逻辑将在一个控制器上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM