gpt4 book ai didi

Angular 在URLS中使用#

转载 作者:行者123 更新时间:2023-12-03 18:32:26 27 4
gpt4 key购买 nike

我目前正在开发一个 URL 解析器,用于格式化和更正相对链接。我指定了一些特殊字符,包括“#”。

我发现当我处理使用 Angular 开发的页面时,这会成为一个问题,因为在 URL 中使用了 #。但是,在阅读 IETF protocol 以进行 URL 命名时,似乎 # 是保留字符。

有人可以向我解释 Angular 如何与 URL 命名交互吗?

最佳答案

路由策略

在 angular 项目中配置应用程序路由时,可以在常规 HTML5 路由 ( PathLocationStrategy ) 或“散列式 URL”路由 ( HashLocationStrategy ) 之间进行选择。

默认为 PathLocationStrategy 但散列式路由可以通过将 {useHash: true} 作为第二个参数传递给 RouterModule.forRoot() 函数来实现

根据 Angular 关于 LocationStrategy and browser URL styles 的官方文档:

Older browsers send page requests to the server when the location URL changes unless the change occurs after a "#" (called the "hash"). Routers can take advantage of this exception by composing in-application route URLs with hashes.



为什么 Angular 支持哈希路由

URL 中的 # 表示 anchor 标识符 ( RFC1738 ),在链接到页面中的特定内容时非常有用。
HashLocationStrategy 的 angular 漏洞是这样一个事实,即 # 符号之后的任何内容都不会发送到服务器 - 这使得它非常适合用于存储应用程序状态。

为什么有用

使用哈希路由在子页面上重新加载页面(或通过书签重新访问),例如
http://localhost:4200/#/articles/35
不向服务器查询子页面,而是返回主应用程序页面
http://localhost:4200/
这样服务器实现只需要知道根页面(这是唯一会被查询的东西)

使用 PathLocationStrategy(默认),需要设置服务器来处理应用程序实现的每个 URL 的请求。

关于 Angular 在URLS中使用#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52563837/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com