Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My factory looks like:

'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);
      }
    }
}]);

It spits out the log, but doesn't change the path. What can I do to make this happen?

like image 636
Shamoon Avatar asked Oct 21 '13 15:10

Shamoon


People also ask

How to change URL path in AngularJS?

To change path URL with AngularJS, $location. path() is passed the new URL as a parameter, and the page is automatically reloaded. This means that if you ever make a change to the URL in an Angular application, then the partial and controller will be reloaded automatically.

What is the purpose of the$ location service in AngularJS?

The $location service parses the URL in the browser address bar (based on the window. location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.

What is HTML5 mode?

In HTML5 mode, the $location service getters and setters interact with the browser URL address through the HTML5 history API. This allows for use of regular URL path and search segments, instead of their hashbang equivalents.


2 Answers

The documentation for $location says:

Note that the setters don't update window.location immediately. Instead, the $location service is aware of the scope life-cycle and coalesces multiple $location mutations into one "commit" to the window.location object during the scope $digest phase.

Hence, if the rejection of the promise has an effect on $location, then you may not see the intended change.

To force a change outside of the angular life-cycle, you can set the hash using window.location and then force a reload of the page. This will, of course, stop execution of any code which follows and erase the session, but that might be what you want if the user is not logged in.

like image 114
musically_ut Avatar answered Sep 28 '22 06:09

musically_ut


There are certain cases where $location will not redirect if it is outside angular's apply cycle. Try wrapping the $location inside the $apply.

$rootScope.$apply( function(){$location.path('/somelocatin'); } );
like image 34
uptownhr Avatar answered Sep 28 '22 07:09

uptownhr