简体   繁体   中英

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.

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.

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? Or should I just create redirector service and inject here? 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.

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

And in logoutController, you can add your code.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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