javascript – 重定向时的AngularJS无限循环

我有一个登录的应用程序,必须决定用户是否可以登录某些页面,如果他们登录或不登录.我遇到的问题是,在达到某个路线时,我不需要模板,但我会调用服务来处理将它们发送到登录页面或让它们继续.服务检查它们是否已登录,如果不是,则使用window.location.href将它们发送到登录路由.

当它到达window.location.href行时,登录控制器被无限初始化(达到10 $digest()迭代)并且在该点之后没有任何工作.在重定向与哈希相关时,我是否遗漏了一些东西?

这只发生在IE9中.循环问题不会发生在chrome或safari中.

路由代码:

angular.module('myApp', []).config(['$routeProvider', function($routeProvider) { 
$routeProvider
  .when('/login', {templateUrl: 'partials/login.html', controller: 'LoginCtrl', title:'Login'})
  .when('/register', {template  : " ", controller:  'RegisterCtrl', title:'Register'})
  .when('/eBooks', {resolve: {redirect: 'LoginRouter'}});
}]);

处理登录路由的服务:

.service('LoginRouter', ['RouteService', '$rootScope', '$window',  function(RouteService, $rootScope, $window) {        

if (!$rootScope.isLoggedIn) {
    RouteService.setModule("eBooks");
    $window.location.href = "#/login"; // Causing infinite loop
}
else {
    var config = $rootScope.config; 
    $rootScope.startLoading();
    $window.location.href = config.EBOOK_URL+ "&bookId=" + config.bookId.replace("-","");
}
}]);

登录控制器:

.controller('LoginCtrl',['$scope' ,'LoginService', function ($scope, LoginService) {
    $scope.user = {mtn: ""};
    $scope.checkUser = function() {
        LoginService.validateUser($scope);
    };
}]); 

注意:我更改了代码只是指向一个带有锚标记的html模板,并且href指向“登录”,它工作得很好.只有当我通过窗口直接触发位置更改时才会卡在循环中.

更新:我从login.html模板中删除了所有内容,以查看html中的某些内容是否导致问题,删除了所有指令以及控制器作用域和rootScope上的任何函数/模型,但问题仍然存在.

更新2我尝试使用角度来强制点击锚点试图绕过问题,但它仍然发生.我注意到一个有趣的事情是,如果我在IE中打开控制台窗口,那么问题首先就不会发生.到底是怎么回事????

最佳答案 我建议使用绝对路径只是为了确保一些不那么聪明的浏览器(IE!)能够理解你的代码.尝试添加原点:

 window.location.href = $window.location.origin + "#/login"; 

另外,我认为你正在使用$window.location.href而不是$location

这是AngularJS官方文档推荐的 – see here

页面重新加载导航

The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API, $window.location.href.

点赞