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

被刻印的时光 ゝ 提交于 2019-11-28 12:31:51

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.

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

This one 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()
}])

Notice that the $rootScope.$apply() is after the $location.path('path') call, for some reason wrapping it inside the $apply call callback as suggested above wasn't working.

Try

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

instead of

$location.path('/login');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!