【问题标题】:Where to put event listening in Angular在 Angular 中将事件监听放在哪里
【发布时间】:2016-08-11 08:43:58
【问题描述】:

在我当前基于模块/组件的架构中,我从 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 服务并在这里注入?这方面的最佳做法是什么?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    这就是我们所遵循的。

    您可以为它定义一个路由,而不是使用js将url重定向到logout.html。

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

    在 logoutController 中,你可以添加你的代码。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多