【问题标题】:AngularJS: Injecting service into a HTTP interceptor (Circular dependency)AngularJS:将服务注入 HTTP 拦截器(循环依赖)
【发布时间】:2013-12-18 00:29:34
【问题描述】:

我正在尝试为我的 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 文档中的 section on $http 似乎显示了一种将依赖项以“常规方式”注入 Http 拦截器的方法。在“Interceptors”下查看他们的代码 sn-p:

// 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');

上面的代码应该去哪里?

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

谢谢,我希望我的问题足够清楚。

【问题讨论】:

  • 只是出于好奇,您在 AuthService 中使用了哪些依赖项(如果有)?我在使用 http 拦截器中的请求方法时遇到了循环依赖问题,这将我带到了这里。我正在使用 angularfire 的 $firebaseAuth。当我从注入器中删除使用 $route 的代码块时(第 510 行),一切都开始工作了。 here 有一个问题,但它是关于在拦截器中使用 $http 的。转到 git!
  • 嗯,就我而言,AuthService 取决于 $window, $http, $location, $q
  • 我有一个案例在某些情况下会在拦截器中重试请求,因此对$http 的循环依赖更短。我发现的唯一解决方法是使用$injector.get,但如果有很好的方法来构造代码以避免这种情况,那就太好了。
  • 看看@rewritten 的回复:github.com/angular/angular.js/issues/2367 为我解决了类似的问题。他的做法是这样的:$http = $http || $injector.get("$http");当然,您可以将 $http 替换为您自己尝试使用的服务。

标签: javascript angularjs


【解决方案1】:

这就是我最终做的事情

  .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 中遇到循环依赖错误。

【讨论】:

  • 使用手动注入 ($injector.get('Auth')) 解决了问题。干得好!
  • 为了避免循环依赖,我正在检查调用了哪个 url。 if(!config.url.includes('/oauth/v2/token') && config.url.includes('/api')){ // 调用 OAuth 服务 }.因此没有更多的循环依赖。至少对我自己来说它有效;)。
  • 完美。这正是我解决类似问题所需要的。谢谢@shaunlim!
  • 我不太喜欢这个解决方案,因为这个服务是匿名的,并且不容易处理测试。在运行时注入更好的解决方案。
  • 这对我有用。基本上是注入使用 $http 的服务。
【解决方案2】:

$http 和 AuthService 之间存在循环依赖关系。

您使用$injector 服务所做的是通过延迟 $http 对 AuthService 的依赖关系来解决先有鸡还是先有蛋的问题。

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

你也可以这样做:

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

【讨论】:

  • 这个答案是如何解决问题的,我没看到? @shaunlim
  • 其实并没有解决,只是指出算法流程不好。
  • 您不能在run() 块中注册拦截器,因为您不能将 $httpProvider 注入到运行块中。您只能在配置阶段执行此操作。
  • 好点重新循环引用,但否则它不应该是一个可接受的答案。这两个要点都没有任何意义
【解决方案3】:

我认为直接使用 $injector 是一种反模式。

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

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

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

【讨论】:

  • 我认为这是一个更优雅的解决方案,因为它不会有任何依赖,我们也可以在很多相关的地方收听这个事件
  • 这不能满足我的需要,因为在调度事件后我无法获得返回值。
【解决方案4】:

糟糕的逻辑导致了这样的结果

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

在您的情况下,Angular 应用程序无论如何都会发送请求,您只需在那里检查授权,然后 JavaScript 将发送请求。

问题的核心

myHttpInterceptor$httpProvider 实例下被调用。你的AuthService 使用$http$resource,在这里你有依赖递归或循环依赖。如果您从 AuthService 中删除该依赖项,您将不会看到该错误。


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

如果你想做干净和自我描述的代码,你必须遵循一些 SOLID 原则。

至少单一职责原则在这种情况下会帮助你很多。

【讨论】:

  • 我认为这个答案措辞不好,但我确实认为它触及了问题的根源。存储当前用户数据登录方式(http 请求)的身份验证服务的问题在于它负责两件事。如果将其拆分为一个服务用于存储当前用户数据,另一个服务用于登录,那么http拦截器只需要依赖“当前用户服务”,不再产生循环依赖。
  • @Snixtor 谢谢!我需要多学点英语,才能更清楚。
【解决方案5】:

如果您只是检查身份验证状态 (isAuthorized()),我建议将该状态放在单独的模块中,例如“Auth”,它只保存状态并且不使用 $http 本身。

app.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.interceptors.push(function ($location, Auth) {
    return {
      'request': function (config) {
        if (!Auth.isAuthenticated() && $location.path != '/login') {
          console.log('user is not logged in.');
          $location.path('/login');
        }
        return config;
      }
    }
  })
}])

认证模块:

angular
  .module('app')
  .factory('Auth', Auth)

function Auth() {
  var $scope = {}
  $scope.sessionId = localStorage.getItem('sessionId')
  $scope.authorized = $scope.sessionId !== null
  //... other auth relevant data

  $scope.isAuthorized = function() {
    return $scope.authorized
  }

  return $scope
}

(我在这里使用 localStorage 将 sessionId 存储在客户端,但您也可以在 $http 调用后将其设置在 AuthService 中)

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 2015-11-30
    • 2021-07-13
    • 2022-01-13
    • 2017-10-27
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多