Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

$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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...