Angular 4 如何在路由没有“#”且无副作用的情况下更改URL?

How can Angular 4 change URL when routing without "#" and no side effects?

在 angular 或其他 SPA 框架的早期版本中,导航过去常常使用 URL 中的 "#" 从一个页面移动到另一个页面,而无需向服务器发出另一个请求.

今天,使用 Angular 4 条路由,我注意到 URL 在没有向服务器发出任何请求的情况下被重写。例如 domain.com/about。我觉得很奇怪。

如果我的 SPA 是从 domain.com/index.html 提供的,对 domain.com/about 的请求应该会有副作用,带来完全不同的页面(例如 about/index.hmtl),而不是内部路由index.html

更改 URL 而不重定向到 URL 中的地址似乎违反了某些内容.. 不是吗?

在 Angular 4 中仅使用客户端怎么可能?

当您在网站上导航时,单击 links、选项卡等 - 这一切都只是客户端。 但是,当您按 F5 或导航到 link 时,例如 /school/6/personList - 服务器应配置为 return index.html.

这就是为什么经常休息 api 是 smth 像 /api/users、/api/emails 等,所以都以 '/api' 开头 - 你可以很容易地重定向index.html.

的所有其他请求

Change URL without redirect to the address in the URL seems to violate something.. dont?

不,这是单页应用程序 (SPA) 的重点,而不是针对每个 URL 更改向服务器发送请求的另一种方式。

Angular路由器有两种定位策略:

navigations used to use "#" in the URL to move from a page to another without make another request to the server.

现在仍然可以通过使用 HashLocationStrategy 使用 Angular,只需使用 {useHash: true} 执行以下操作即可:

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes, {useHash: true})
    ],

Today, using Angular 4 routes, I notice that the URL was rewritten without any request to the server

那是因为默认使用PathLocationStrategy

无论策略如何,如果您使用 Angular 路由,来自应用程序的所有 URL 更改都将由路由器处理,并且不会向服务器发送任何请求。例如下面的代码:

Router.navigateByUrl('/my')

PathLocationStrategy的情况下会生成如下URL:

host/my

并且在 HashLocationStrategy 的情况下,它会像这样生成 ULR:

host#my