AngularJS:将服务注入HTTP拦截器(循环依赖)

 手机用户2502937257 发布于 2023-02-09 17:56

我正在尝试为我的AngularJS应用程序编写HTTP拦截器来处理身份验证.

这段代码有效,但我担心手动注入服务,因为我认为Angular应该自动处理:

    app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push(function ($location, $injector) {
        return {
            'request': function (config) {
                //injected manually to get around circular dependency problem.
                var AuthService = $injector.get('AuthService');
                console.log(AuthService);
                console.log('in request interceptor');
                if (!AuthService.isAuthenticated() && $location.path != '/login') {
                    console.log('user is not logged in.');
                    $location.path('/login');
                }
                return config;
            }
        };
    })
}]);

我开始做的事情,但遇到循环依赖问题:

    app.config(function ($provide, $httpProvider) {
    $provide.factory('HttpInterceptor', function ($q, $location, AuthService) {
        return {
            'request': function (config) {
                console.log('in request interceptor.');
                if (!AuthService.isAuthenticated() && $location.path != '/login') {
                    console.log('user is not logged in.');
                    $location.path('/login');
                }
                return config;
            }
        };
    });

    $httpProvider.interceptors.push('HttpInterceptor');
});

我担心的另一个原因是Angular Docs中关于$ http的部分似乎显示了一种方法来将依赖关系注入"常规方式"到Http拦截器中.在"拦截器"下查看他们的代码片段:

// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
    // optional method
    'request': function(config) {
      // do something on success
      return config || $q.when(config);
    },

    // optional method
   'requestError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    },



    // optional method
    'response': function(response) {
      // do something on success
      return response || $q.when(response);
    },

    // optional method
   'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    };
  }
});

$httpProvider.interceptors.push('myHttpInterceptor');

上面的代码应该放在哪里?

我想我的问题是这样做的正确方法是什么?

谢谢,我希望我的问题很清楚.

4 个回答
  • 这就是我最终做的事情

      .config(['$httpProvider', function ($httpProvider) {
            //enable cors
            $httpProvider.defaults.useXDomain = true;
    
            $httpProvider.interceptors.push(['$location', '$injector', '$q', function ($location, $injector, $q) {
                return {
                    'request': function (config) {
    
                        //injected manually to get around circular dependency problem.
                        var AuthService = $injector.get('Auth');
    
                        if (!AuthService.isAuthenticated()) {
                            $location.path('/login');
                        } else {
                            //add session_id as a bearer token in header of all outgoing HTTP requests.
                            var currentUser = AuthService.getCurrentUser();
                            if (currentUser !== null) {
                                var sessionId = AuthService.getCurrentUser().sessionId;
                                if (sessionId) {
                                    config.headers.Authorization = 'Bearer ' + sessionId;
                                }
                            }
                        }
    
                        //add headers
                        return config;
                    },
                    'responseError': function (rejection) {
                        if (rejection.status === 401) {
    
                            //injected manually to get around circular dependency problem.
                            var AuthService = $injector.get('Auth');
    
                            //if server returns 401 despite user being authenticated on app side, it means session timed out on server
                            if (AuthService.isAuthenticated()) {
                                AuthService.appLogOut();
                            }
                            $location.path('/login');
                            return $q.reject(rejection);
                        }
                    }
                };
            }]);
        }]);
    

    注意:$injector.get调用应该在拦截器的方法内,如果你试图在别处使用它们,你将继续在JS中获得循环依赖性错误.

    2023-02-09 17:58 回答
  • $ http和您的AuthService之间存在循环依赖关系.

    你通过使用该$injector服务正在做的是通过延迟$ http对AuthService的依赖来解决鸡和蛋的问题.

    我相信你所做的实际上是最简单的方法.

    你也可以这样做:

    稍后注册拦截器(在run()块而不是config()块中执行此操作可能已经成功).但是你能保证$ http还没有被调用吗?

    当您通过调用AuthService.setHttp()或其他方式注册拦截器时,"将"http"手动注入"AuthService .

    ...

    2023-02-09 17:58 回答
  • 我认为直接使用$ injector是一个反模式.

    打破循环依赖的一种方法是使用一个事件:不是注入$ state,而是注入$ rootScope.做,而不是直接重定向

    this.$rootScope.$emit("unauthorized");
    

    angular
        .module('foo')
        .run(function($rootScope, $state) {
            $rootScope.$on('unauthorized', () => {
                $state.transitionTo('login');
            });
        });
    

    2023-02-09 17:58 回答
  • 糟糕的逻辑造就了这样的结

    实际上,在Http Interceptor中没有用户创作的用户创作.我建议将所有HTTP请求包装成单个.service(或.factory,或.provider),并将其用于所有请求.每次调用函数时,都可以检查用户是否登录.如果一切正常,请允许发送请求.

    在您的情况下,Angular应用程序将在任何情况下发送请求,您只需在那里检查授权,然后JavaScript将发送请求.

    你的问题的核心

    myHttpInterceptor$httpProvider实例下调用.您的AuthService用途$http,或者$resource,此处您具有依赖性递归或循环依赖性.如果你从中删除那个依赖项AuthService,那么你将不会看到该错误.


    同样正如@Pieter Herroelen指出的那样,你可以将这个拦截器放在你的模块中module.run,但这更像是一个黑客,而不是一个解决方案.

    如果您需要执行干净且自我描述的代码,则必须遵循一些SOLID原则.

    在这种情况下,至少单一责任原则将对您有所帮助.

    2023-02-09 17:58 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有