本文介绍了使用浏览器后退时,Angular $location 不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人遇到过这种行为吗?关于它没有太多提及,其他帖子性质不同.这似乎与有关浏览器行为的文档不一致.
Has anyone run across this behaviour? There isn't much mentioned about it, and the other posts are different in nature. This appears to be inconsistent w/ documentation about browser behaviour.
用户访问时与浏览器同步网址
- 更改地址栏.
- 点击后退或前进按钮(或点击历史链接).
- 点击链接.
https://docs.angularjs.org/api/ng/service/$location#!
https://docs.angularjs.org/api/ng/service/$location#!
发生了什么:
- 加载页面 - 哈希更新 (http://localhost:9000/#/)
- 单击开始" - 通过函数更新 $location.$$path 以更新哈希并加载新视图 (http://localhost:9000/#/guide)
- 棘手!用户单击浏览器中的后退按钮,哈希更新回 http://localhost:9000/#/ 但进行调试告诉我 $location.$$path 仍然认为我们在 $location.$$path =/guide - 基于位置路径的逻辑不起作用.
- Load page - hash updates (http://localhost:9000/#/)
- Click 'Start' - update $location.$$path via function to update hash and load new view (http://localhost:9000/#/guide)
- Tricky! User clicks back-button in browser, hash updates back to http://localhost:9000/#/ but debug tells me $location.$$path still thinks we are at $location.$$path = /guide - logic based on location path doesn't work.
这是现场帮助调试的观察者:
This is a watcher to on location to help debug:
// listen for the event in the relevant $scope
$rootScope.$on('locationChange', function (event, data) {
console.log(data);
});
//Call locationChange watch at anytime the page is loaded
$scope.$emit('locationChange', $location.$$path);
路线如下:
$routeProvider
.when('/guide', {
templateUrl: 'views/guide.html',
controller: 'GuideController',
controllerAs: 'guide'
})
.when('/', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
controllerAs: 'about'
})
.otherwise({
redirectTo: '/'
});
推荐答案
我是如何解决这个问题的:
How I solved this:
var pop = 0;
window.onpopstate = function(event) {
if (document.location.pathname === '/' && pop > 1) {
pop = 0;
document.location = 'http://localhost:9000/';
}
pop++;
};
这篇关于使用浏览器后退时,Angular $location 不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!