Karol Klepacki Karol Klepacki - 1 year ago 59
AngularJS Question

Where to put event listening in Angular

In my current module/component-based architecture I'm intercepting all

from API calls, and if I come across
401 Unauthorized
, I'm redirecting to the logout page.

My current code is:

.factory('authHTTPInterceptor', authHTTPInterceptor)
.config(['$httpProvider', function($httpProvider) {

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

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

I want to move
logic to another entity, and emit
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
, or something else? Or should I just create
service and inject here? What's best practice for this?

Answer Source

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.