角平台位置pushState不起作用

角平台位置pushState不起作用

本文介绍了角平台位置pushState不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在平台第一次加载时向浏览器历史记录注入新状态,因此当用户单击浏览器后退按钮时,它应该会登陆到应用程序的主页。

I want to inject a new state to browser history when the platform is loaded for the 1st time so when the user clicks browser back button it should land to the home page of the app.

我尝试使用
添加新状态1. PlatformLocation pushState()
2. window.history.pushState()

I tried to add new state using1. PlatformLocation pushState()2. window.history.pushState()

location.pushState(null, 'home', 'home');
// window.history.pushState(null, 'home', 'home');

我什至尝试给出完整的URL

I even tried giving full URL

location.pushState(null, 'home', 'http://localhost:4200/home');
// window.history.pushState(null, 'home', 'http://localhost:4200/home');

它确实向浏览器历史记录添加了新状态,但是当我单击浏览器后退按钮时,没有任何反应,即我仍在同一页面上,但仅新添加的状态从浏览器历史记录中删除。

It does add a new state to browser history but when I click browser back button, nothing happens i.e. I am still in the same page but only the newly added state is removed from the browser history.

推荐答案

我已经在您的回答中此处有其他问题:

I already answered this in your other question here: https://stackoverflow.com/a/55511843/11289490

当您调用 history.pushState 时,它只会在历史记录中添加具有所需网址的一页,但不会加载该网页或检查它是否存在。

When you call to the history.pushState , it only adds one page to the history with the url you want, but It doesn't load the webpage or check if it exists.

如果要在导航时加载主页,可以执行以下操作:

If you want to load the home page when you navigate back you can do something like this :

 let locat = location.href;
    if (!!window.location.pathname && window.location.pathname !== '/') {
        history.replaceState(null,null,location.origin);
        history.pushState(null, null,locat);
    }

它会添加带有网址库的历史记录,然后在完整的网址中添加历史。

It adds a history with the url base and then add the complete url in the history.

这篇关于角平台位置pushState不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 13:00