$ location.path doesn't change in factory with AngularJS

My factory looks like this:

'use strict'; angular.module('myApp') .factory('httpInterceptor',['$q','$location', '$rootScope', function($q, $location, $rootScope){ return { response: function(response) { if(response.success === false) { console.log("Redirecting"); $location.path('/login'); return $q.reject(response); } return response || $q.when(response); } } }]); 

He spits out a magazine, but does not change the path. What can I do to make this happen?

+5
source share
4 answers

The documentation for $ location says:

Note that setters do not update window.location immediately. Instead, the location service is aware of the region’s life cycle and combines several $ location mutations into one “commit” to the window.location object during the region’s $ digest phase.

Therefore, if a rejection of a promise affects $location , you may not see the proposed change.

To force a change outside the angular life cycle, you can set hash with window.location , and then force the page to reload. This, of course, will stop executing any of the following code and delete the session, but it may be what you want if the user is not logged in.

+10
source

There are certain cases where $ location will not be redirected if it is outside the angular apply loop. Try wrapping $ location inside $ apply.

 $rootScope.$apply( function(){$location.path('/somelocatin'); } ); 
+6
source

This worked for me on Angular 1.3.14

 myServices.factory('Factory', ['$rootScope', '$location', function ($rootScope, $location) { // do something and redirect $location.path('path') $rootScope.$apply() }]) 

Note that $rootScope.$apply() after calling $location.path('path') , for some reason, wrapping it inside the $ apply callback, as suggested above, does not work.

+3
source

Try

 $location.path('#/login'); 

instead

 $location.path('/login'); 
0
source

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


All Articles