我有一个可以登录的应用程序,它必须决定用户是否可以访问某些页面(如果他们已登录)。我遇到的问题是,在到达某条路线后,我不需要模板,但我调用了一项服务来处理将它们发送到登录页面或让它们继续。该服务检查他们是否已登录,如果没有,是否使用 window.location.href 将他们发送到登录路由。
当它到达 window.location.href 行时,登录 Controller 被无限初始化(达到 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 :
.controller('LoginCtrl',['$scope' ,'LoginService', function ($scope, LoginService) {
$scope.user = {mtn: ""};
$scope.checkUser = function() {
LoginService.validateUser($scope);
};
}]);
注意:我更改了代码以指向带有 anchor 标记和指向“登录”的 href 的 html 模板,它工作得很好。只有当我直接通过窗口触发位置更改时,它才会卡在循环中。
更新:我删除了 login.html 模板中的所有内容以查看是否是 html 中的某些内容导致了问题,删除了所有指令以及 Controller 作用域和 rootScope 上的所有函数/模型,并且仍然问题发生了。
更新 2 我尝试使用 angular 强制点击 anchor 以尝试绕过该问题,但它仍然发生。我注意到的一件有趣的事情是,如果我在 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.
关于javascript - 重定向时 AngularJS 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19276781/