AngularJS中if分支内$timeout在window.location.href后失效问题求助
AngularJS跳转页面后$timeout失效的问题解决
问题原因
执行window.location.href跳转到新页面时,当前页面的JavaScript环境(包括AngularJS应用、控制器及所有未执行的定时器)会被立即销毁,所以后续的$timeout根本没有机会触发。而else分支中没有页面跳转,当前环境保持正常,$timeout自然能正常运行。
解决方案
方案1:在目标页面中设置定时器
既然跳转后当前页面的代码无法继续执行,就把跳转逻辑放到第一个跳转的目标页面(home.html#!/employee)的控制器中:
angular.module('Route').controller('EmployeeController', ['$timeout', function($timeout) { // 页面加载完成后,5秒自动跳转到首页 $timeout(function() { window.location.href = "http://localhost:8080"; }, 5000); }]);
方案2:使用AngularJS路由实现无刷新跳转(推荐)
如果你的页面属于同一个AngularJS单页应用,尽量避免用window.location.href刷新页面,改用Angular的$location服务(或ui-router的$state)进行路由跳转,这样能保留应用上下文,$timeout可以正常工作:
// 注入$location服务到控制器 angular.module('Route').controller('LoginController', ['$scope', 'LoginService', '$timeout', '$location', function ($scope, LoginService, $timeout, $location) { $scope.credentials = { Login: '', Password: '' }; $scope.login = function () { LoginService.login($scope.credentials) .then(function (response) { console.log("Response data: ", response.data); if (response.data.length > 0) { // 单页应用内跳转到employee路由 $location.path('/employee'); // 5秒后跳转到首页路由 $timeout(function () { $location.path('/'); }, 5000); } else { alert("请检查您的账号信息"); $scope.credentials.Password = ''; } }) .catch(function (error) { console.error("Error", error); }); }; }]);
注意:这种方式需要确保你的Angular应用已经配置了对应的路由规则(比如通过$routeProvider定义/employee和/的路由)。
内容的提问来源于stack exchange,提问作者Rvdux
相关产品推荐
相关产品推荐

