Angular2 pathLocationStrategy: url change cause pa

2019-06-17 04:45发布

While using HashLocationStrategy I can change route by changing address in browser's address bar by hand without page reload. I.e. navigation from mysite/#/home to mysite/#/profile

However, if I use PathLocationStrategy (it is default location strategy), I have unwanted page reload, when I try to do the same thing. I.e. navigation from mysite/home to mysite/profile

Is it possible to fix this?

I am using Angular 2.0.0-beta17

2条回答
不美不萌又怎样
2楼-- · 2019-06-17 04:48

That's "as designed". When you only change the #... then there is nothing to send to the server. The #... part is always only processed by the browser and never sent to the server.

When you change the part before #, and if you don't have a # than everything is the before-#-part then the browser needs to make a new request to the server to fetch the URL.

If you use the window.history... API (https://developer.mozilla.org/en-US/docs/Web/API/History_API) then you tell the browser to just update the URL bar but don't call out to the server. The Angular router uses this API therefore this works from within the app or when you use the back or forward button but not when you manually change the URL.

查看更多
叛逆
3楼-- · 2019-06-17 04:50

If you want to use HTML5 paths (PathLocationStrategy) without the NG2 page-refresh on route change, you must use the routerLink directive, ie:

<a [routerLink]="['/my-page']">My Page</a>
<a [routerLink]="['/my-other-page']">My Other Page</a>

At the @NgModule init imports:

RouterModule.forRoot([
  {path: '',              component: DefaultComponent},
  {path: 'my-page',       component: MyPageComponent},
  {path: 'my-other-page', component: MyOtherPageComponent}
]);
查看更多
登录 后发表回答