angularjs – 循环依赖关系找到:$http < - $templateFactory < - $view < - $state

前端之家收集整理的这篇文章主要介绍了angularjs – 循环依赖关系找到:$http < - $templateFactory < - $view < - $state前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个当前401检查,我运行与$位置工作正常。但是我想把它交换到$ state并使用ui-router代替。当我这样做,我得到一个错误代码
  1. Circular dependency found: $http <- $templateFactory <- $view <- $state <- authHttpResponseInterceptor <- $http <- $compile

我当前的代码看起来很好,因为我检查某些路径,并允许没有登录用户查看它们:

  1. /* Look for 401 auth errors and then redirect */
  2. .factory('authHttpResponseInterceptor',['$q','$location',function($q,$location) {
  3.  
  4. return {
  5. response: function(response){
  6. if (response.status === 401) {
  7. }
  8.  
  9. return response || $q.when(response);
  10. },responseError: function(rejection) {
  11. var reservedPaths = ['/','/login','/connect','/event'];
  12. if (rejection.status === 401 && _.contains(reservedPaths,$location.path().trim())) {
  13. $location.path('/welcome');
  14.  
  15. }
  16. return $q.reject(rejection);
  17. }
  18. };
  19. }])
  20. .config(['$httpProvider',function($httpProvider) {
  21. //Http Intercpetor to check auth failures for xhr requests
  22. $httpProvider.interceptors.push('authHttpResponseInterceptor');
  23. }]);

添加代码如下:

  1. /* Look for 401 auth errors and then redirect */
  2. .factory('authHttpResponseInterceptor',**'$state',** function($q,$location,**$state**) {
  3.  
  4. return {
  5. response: function(response){
  6. if (response.status === 401) {
  7. }
  8.  
  9. return response || $q.when(response);
  10. },'/mycube',$location.path().trim())) {
  11. **$state.go('home');**
  12.  
  13. }
  14. return $q.reject(rejection);
  15. }
  16. };
  17. }])
  18. .config(['$httpProvider',function($httpProvider) {
  19. //Http Intercpetor to check auth failures for xhr requests
  20. $httpProvider.interceptors.push('authHttpResponseInterceptor');
  21. }]);

为什么添加状态导致此问题,当它与位置正常工作?

看来$ state服务导致与$ http服务的循环依赖。这可能是由于templateFactory(参见 https://github.com/angular-ui/ui-router/blob/master/src/templateFactory.js)被注入$ http服务以及拦截器本身由$ http服务组成的事实造成的。

为了解决这个循环依赖问题,你可以使用$ injector服务将$ state服务连接到你的拦截器。见修改后的代码

  1. /* Look for 401 auth errors and then redirect */
  2. module.factory('authHttpResponseInterceptor','$injector',$injector) {
  3. return {
  4. response: function(response){
  5. if (response.status === 401) {
  6. }
  7.  
  8. return response || $q.when(response);
  9. },responseError: function(rejection) {
  10. var reservedPaths = ['/','/event'];
  11. if (rejection.status === 401 && _.contains(reservedPaths,$location.path().trim())) {
  12. var stateService = $injector.get('$state');
  13. stateService.go('home');
  14. }
  15. return $q.reject(rejection);
  16. }
  17. };
  18. }]);

您可以在这里了解更多关于$ injector服务的信息:https://docs.angularjs.org/api/auto/service/ $ injector

重要

我建议使用状态更改事件(参见https://github.com/angular-ui/ui-router/wiki#state-change-events)使用$ stateChangeError监视错误,并检查从401返回的错误

猜你在找的Angularjs相关文章