AngularJS redirect does not occur in interceptor

I use a very simple interceptor to check the responseRejection for 403 Access Forbidden to redirect users to the login, but it is not redirected. I can console.log right before the line before and after $ location.path, and this never happens. Has anyone else this happened? I stared at it a little now ... Initially, I didn’t even want to use $ location, but I can’t enter ui.router without getting a circular dependency, and I also can’t figure out how to get rid of such a $ location, it was assumed that I will move while I thought about it.

.factory('AuthInterceptor', ['$q', '$location', function( $q, $location ) { var service = { responseError: function( responseRejection ) { // Authorization issue, access forbidden if( responseRejection.status === 403 ) { // TODO: show a login dialog, and/or redirect to login console.log("Response rejected. Redirecting to login..."); $location.path('/login'); $location.replace(); console.log("Not so much with the redirecting... I'm still here"); } // Propagate error to any chained promise handlers return $q.reject( responseRejection ); } } return service; }]) 
+5
source share
1 answer

When setting the window's location.href using location.href it sets the location immediately and stops executing scripts, but changing the location will only work when the current script path is completed. This is why you see the instructions below href. It is also not a blocking activity (as opposed to a warning or a hint). When you adjust your location using the angular wrapper, it takes effect after the digest cycle. And you have a real circular dependency problem when introducing $state into the $http interceptor. To overcome this, you can get an instance of $state using the $injector.

 .factory('AuthInterceptor', ['$q', '$injector', function( $q, $injector ) { var $state; var service = { responseError: function( responseRejection ) { // Authorization issue, access forbidden if( responseRejection.status === 403 ) { // TODO: show a login dialog, and/or redirect to login console.log("Response rejected. Redirecting to login..."); _setState('login'); console.log("Not so much with the redirecting... I'm still here"); } // Propagate error to any chained promise handlers return $q.reject( responseRejection ); } } function _setState(stateName){ if(!$state) { $injector.get('$state'); //Or just get $state from $injector always it is anyways the dependency container and service are singletons } $state.go(stateName); } return service; }]); 
+2
source

Source: https://habr.com/ru/post/1205633/


All Articles