javascript - Angular platformLocation pushState 不起作用
问题描述
我想在第一次加载平台时向浏览器历史记录注入一个新状态,因此当用户单击浏览器后退按钮时,它应该登陆应用程序的主页。
我尝试使用 1. PlatformLocation pushState() 2. window.history.pushState() 添加新状态
location.pushState(null, 'home', 'home');
// window.history.pushState(null, 'home', 'home');
我什至尝试给出完整的 URL
location.pushState(null, 'home', 'http://localhost:4200/home');
// window.history.pushState(null, 'home', 'http://localhost:4200/home');
它确实向浏览器历史记录添加了一个新状态,但是当我单击浏览器后退按钮时,什么也没有发生,即我仍在同一页面中,但只有新添加的状态从浏览器历史记录中删除。
解决方案
我已经在您的其他问题中回答了这个问题:https ://stackoverflow.com/a/55511843/11289490
当您调用 时history.pushState
,它只会在历史记录中添加一个带有您想要的 url 的页面,但它不会加载网页或检查它是否存在。
如果您想在返回时加载主页,您可以执行以下操作:
let locat = location.href;
if (!!window.location.pathname && window.location.pathname !== '/') {
history.replaceState(null,null,location.origin);
history.pushState(null, null,locat);
}
它使用 url 基础添加历史记录,然后在历史记录中添加完整的 url。
推荐阅读
- python - 如何使用 python IMAP 提取多部分电子邮件的正文并保存附件?
- linux - 无法让 Resque 工作人员在重新启动时启动
- c# - 我正在尝试使用实体框架进行急切加载,其中我在区域和客户端之间具有一对多关系
- reactjs - 尝试使用 Heroku 部署 Django-React 时启动脚本出错
- vue.js - 我在 Vue 2 中使用 Swiper.js 做错了什么?
- javascript - Jest not.toThrowError() 在测试中无法使用 jest.spyOn(component.methods, 'mymethod')
- javascript - WebWorker 可以充当服务器吗?
- oop - 如何从具有多个参数的多个类继承
- r - 如何将两个数据框与R中的两个匹配列合并
- r - 从 OSX 上的命令行调用 R