当前位置: 首页 > 面试题库 >

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

施飞鸿
2023-03-14
问题内容

我正在尝试为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');

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

我想我的问题是执行此操作的正确方法是什么?

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


问题答案:

您在$ http和AuthService之间具有循环依赖关系。

您通过使用该$injector服务所做的事情是通过延迟AuthService上$ http的依赖关系来解决“鸡与蛋”问题。

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

您还可以通过以下方式执行此操作:

  • 稍后注册拦截器(在一个run()块而不是一个config()块中这样做可能已经成功了)。但是可以保证$ http还没有被调用吗?
  • 通过调用AuthService.setHttp()或其他方式注册拦截器时,将$ http手动“注入”到AuthService中。


 类似资料:
  • 问题内容: 我正在努力实现的目标 如果$ http请求返回401错误,我想过渡到某个状态(登录)。因此,我创建了一个$ http拦截器。 问题 当我试图将’$ state’插入拦截器时,我得到了循环依赖。为什么以及如何解决? 码 问题答案: 修复 使用服务获取对服务的引用。 原因 angular-ui-router将服务作为依赖项注入,然后在分派拦截器时在其内部创建对自身的循环引用。 如果您尝试将

  • 我们正在构建一个应用程序,我们需要将实体更新登录到历史表中。我试图通过Hibernate拦截器来实现这一点,我们可以设法获得所有的更改,但很难将它们插入审计表。 我的JPA配置 我的拦截器 } 在方法afterTransactionCompletion中,我需要将所有审计实体写入DB,Autowire不工作,因为这不是spring管理的bean,是否有任何方法可以在此方法中获取DB会话,以便我可以

  • 问题内容: 当我尝试将$ http注入到覆盖的工厂中时,出现错误: 未捕获的错误:[$ injector:cdep]找到循环依赖项:$ http <-$ exceptionHandler <-$ rootScope 任何想法如何解决?如果我使用[]注入,则$ http是未定义的 编辑 ___ _ ___ ___ _ 根据下面的答案,我尝试了: 但我仍然收到循环错误: 未捕获的错误:[$ injec

  • 问题内容: 我写了一个AngularJS服务,我想对其进行单元测试。 我的app.js文件已注册: 我可以测试DI是否像这样工作: 这证明了可以通过DI框架创建服务,但是接下来我要对服务进行单元测试,这意味着要模拟注入的对象。 我该怎么做呢? 我试过将我的模拟对象放在模块中,例如 并将服务定义重写为: 但是后者似乎停止了DI所创建的所有服务。 有人知道我可以如何为单元测试模拟注入的服务吗? 谢谢

  • 本文向大家介绍详解AngularJS中的http拦截,包括了详解AngularJS中的http拦截的使用技巧和注意事项,需要的朋友参考一下 http拦截,即$http服务允许我们与服务端交互,有时候我们希望在发出请求之前以及收到响应之后做些事情。 $httpProvider包含了一个interceptors的数组。 我们这样创建一个interceptor。 接着注册interceptor.  以下

  • 问题内容: 我似乎无法让$ httpProvider.interceptors实际进行拦截。我在JSFiddle上创建了一个示例,该示例记录了拦截器运行的时间以及$ http响应成功的时间。在成功返回响应之后,将运行请求拦截器。这似乎有些倒退。 我不能使用transformRequest,因为我需要更改配置中的参数。该部分未显示在示例中。 我正在使用AngularJS 1.1.5 http://j