我有一个当前401检查,我运行与$位置工作正常。但是我想把它交换到$ state并使用ui-router代替。当我这样做,我得到一个错误代码:
- Circular dependency found: $http <- $templateFactory <- $view <- $state <- authHttpResponseInterceptor <- $http <- $compile
我当前的代码看起来很好,因为我检查某些路径,并允许没有登录的用户查看它们:
- /* Look for 401 auth errors and then redirect */
- .factory('authHttpResponseInterceptor',['$q','$location',function($q,$location) {
- return {
- response: function(response){
- if (response.status === 401) {
- }
- return response || $q.when(response);
- },responseError: function(rejection) {
- var reservedPaths = ['/','/login','/connect','/event'];
- if (rejection.status === 401 && _.contains(reservedPaths,$location.path().trim())) {
- $location.path('/welcome');
- }
- return $q.reject(rejection);
- }
- };
- }])
- .config(['$httpProvider',function($httpProvider) {
- //Http Intercpetor to check auth failures for xhr requests
- $httpProvider.interceptors.push('authHttpResponseInterceptor');
- }]);
- /* Look for 401 auth errors and then redirect */
- .factory('authHttpResponseInterceptor',**'$state',** function($q,$location,**$state**) {
- return {
- response: function(response){
- if (response.status === 401) {
- }
- return response || $q.when(response);
- },'/mycube',$location.path().trim())) {
- **$state.go('home');**
- }
- return $q.reject(rejection);
- }
- };
- }])
- .config(['$httpProvider',function($httpProvider) {
- //Http Intercpetor to check auth failures for xhr requests
- $httpProvider.interceptors.push('authHttpResponseInterceptor');
- }]);
为什么添加状态导致此问题,当它与位置正常工作?
看来$ state服务导致与$ http服务的循环依赖。这可能是由于templateFactory(参见
https://github.com/angular-ui/ui-router/blob/master/src/templateFactory.js)被注入$ http服务以及拦截器本身由$ http服务组成的事实造成的。
为了解决这个循环依赖问题,你可以使用$ injector服务将$ state服务连接到你的拦截器。见修改后的代码:
- /* Look for 401 auth errors and then redirect */
- module.factory('authHttpResponseInterceptor','$injector',$injector) {
- return {
- response: function(response){
- if (response.status === 401) {
- }
- return response || $q.when(response);
- },responseError: function(rejection) {
- var reservedPaths = ['/','/event'];
- if (rejection.status === 401 && _.contains(reservedPaths,$location.path().trim())) {
- var stateService = $injector.get('$state');
- stateService.go('home');
- }
- return $q.reject(rejection);
- }
- };
- }]);
您可以在这里了解更多关于$ injector服务的信息:https://docs.angularjs.org/api/auto/service/ $ injector
重要
我建议使用状态更改事件(参见https://github.com/angular-ui/ui-router/wiki#state-change-events)使用$ stateChangeError监视错误,并检查从401返回的错误。