【问题标题】:how to trigger url changes in single page applications如何在单页应用程序中触发 url 更改
【发布时间】:2019-01-23 10:57:03
【问题描述】:

我在模板中创建了一个 Web 组件并托管在 Angular 应用程序中。我想跟踪或触发 Angular 应用程序中的 url 更改,但 Angular 中的路由不会触发窗口上的本机 hashchange 事件。

有什么方法可以触发 Angular 应用程序的 url 更改,因为我想在我的 web 组件中捕获 url 更改

I have tried below code which is written in stencil to listen for url change but its not getting trigger
 @Listen('window:hashchange')
   onListHandle (event) {
     alert('location: ' + document.location + ', state-hash: ' + JSON.stringify(event.state))
   }
   @Listen('window:popstate')
   onpopstate (event) {
     alert('location: ' + document.location + ', state-popstate: ' + JSON.stringify(event.state))
   }

【问题讨论】:

  • 请告诉我们您的尝试
  • 确保在发布问题时添加一些代码示例
  • 在 SPA 中,您应该使用 RouterActivatedRoute 服务来触发和处理 url 更改。

标签: javascript angular


【解决方案1】:

HTML5 引入了 history.pushState() 和 history.replaceState() 方法,允许您添加和修改历史条目, 分别。这些方法与 window.onpopstate 事件。 Link

示例

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 2011-10-28
    • 2020-03-30
    • 1970-01-01
    • 2021-08-06
    • 2021-01-25
    • 1970-01-01
    相关资源
    最近更新 更多