簡體   English   中英

AngularJS:將服務注入HTTP攔截器(循環依賴)

[英]AngularJS: Injecting service into a HTTP interceptor (Circular dependency)

我正在嘗試為我的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');

上面的代碼應該放在哪里?

我想我的問題是這樣做的正確方法是什么?

謝謝,我希望我的問題很清楚。

這就是我最終做的事情

  .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中獲得循環依賴性錯誤。

$ http和您的AuthService之間存在循環依賴關系。

你通過使用$injector服務正在做的是通過延遲$ http對AuthService的依賴來解決雞與蛋的問題。

我相信你所做的實際上是最簡單的方法。

你也可以這樣做:

  • 稍后注冊攔截器(在run()塊而不是config()塊中執行此操作可能已經完成了這一操作)。 但是你能保證$ http還沒有被調用嗎?
  • 當您通過調用AuthService.setHttp()或其他東西注冊攔截器時,“將”http“手動注入” AuthService.setHttp()
  • ...

我認為直接使用$ injector是一個反模式。

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

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

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

糟糕的邏輯造就了這樣的結

實際上,在Http Interceptor中沒有用戶創作的用戶創作。 我建議將所有HTTP請求包裝成單個.service(或.factory,或.provider),並將其用於所有請求。 每次調用函數時,都可以檢查用戶是否登錄。 如果一切正常,請允許發送請求。

在您的情況下,Angular應用程序將在任何情況下發送請求,您只需在那里檢查授權,然后JavaScript將發送請求。

你的問題的核心

myHttpInterceptor$httpProvider實例下$httpProvider 您的AuthService使用$http$resource ,這里有依賴遞歸或循環依賴。 如果從AuthService刪除該依賴AuthService ,則不會發現該錯誤。


同樣正如@Pieter Herroelen指出的那樣,你可以將這個攔截器放在你的模塊module.run ,但這更像是一個黑客,而不是一個解決方案。

如果您需要執行干凈且自我描述的代碼,則必須遵循一些SOLID原則。

在這種情況下,至少單一責任原則將對您有所幫助。

如果您只是檢查Auth狀態(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中設置它)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM