在我当前的应用程序中,每当用户单击浏览器上的“刷新”按钮时,应用程序就会再次加载并将用户重定向到主页。 我需要保持在同一页面上(无需再次加载应用程序)。我浏览了 StackOverflow 中的许多链接,但找不到我正在寻找的确切解决方案。任何帮助将不胜感激。
我使用 Angular 1.3.17 和 $stateProvider 在状态之间进行路由。我将所有数据存储在 $rootScope 中,每当用户单击刷新时,$rootScope 就会被销毁,并且必须再次重新加载应用程序
我的目标是防止应用程序加载并仅加载用户当前正在使用的页面。
如果你能通过root检测到要恢复和显示的页面和数据,我认为这是正确的解决方案。否则,您可以寻找一个插件来存储本地存储中所需的数据。加载页面时,您可以使用存储的数据将用户重定向到提供的页面
出于充分的理由,无法阻止用户重新加载/离开页面。但是在重新加载之前会触发两个事件,您可以让浏览器要求用户留下来。
angular.element($window).on('beforeunload', ()=>{
var askUserToLeave = true /*your condition here*/;
if (askUserToLeave) {
return '';/*let this empty, cause newer browser dont care about the string input*/
}
});
如果用户确认页面离开,您仍然可以在重新加载之前做最后的事情
angular.element($window).on('unload', ()=>{
//your code here
//e.g. save the $rootscope to localstorage/sessionstorage
});
如前所述,您可以对路线更改做出反应(并防止!)(当用户单击页面上的链接按钮时触发,但当用户通过浏览器重新加载时它没有帮助)。
$rootScope.$on('$routeChangeStart', function (event, next, current) {
if (true/*your condition here*/) {
event.preventDefaults()
}
});
最终在 $rootScope 上保存很多东西并不是一种优雅的方式,而且你正在失去 Angular 封装的好处。如果您想让一些(!)信息“防重新加载”,我建议将它们保存在 sessionStorage (关闭选项卡时被删除)或 localStorage (持续存在,当您清理浏览器缓存或在你的代码)。我强烈建议使用 ngStorage 与 sessionStorage/localStorage 一起使用,就像这样:
$localStorage.foo = 'bar';
$sessionStorage.bar = 'foo';
//reload
console.log($localStorage.foo);//outputs: bar
console.log($sessionStorage.bar);//outputs: foo
https://github.com/gsklee/ngStorage
您可以这样安装:
npm i -S ngStorage
祝你好运:)
没有任何有效的方法可以阻止用户重新加载页面。解决
$rootScope
中的数据不被破坏的最佳方法是将所有数据存储在localStorage
中,并且每次再次加载应用程序时,都应从$rootScope
中分配localStorage
中所需的值。
所以我的观点是将基本值存储在 localStorage 中,例如
let neededData = JSON.parse(localStorage.getItem('yourData'));
并且每次重新加载应用程序时,在应用程序的 ngOnInit() 中保留一个函数,该函数会将本地存储中所需的值分配给
$rootScope
变量,例如
this.$rootScope.data = localStorage.getItem('yourData');
希望有帮助!
// App 组件构造函数中的示例
constructor(private router: Router) {
this.subscription = router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
browserRefresh = !router.navigated;
}
});
}