Angular2 pathLocationStrategy: url change cause page reload

烈酒焚心 提交于 2020-01-03 08:26:51

问题


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


回答1:


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.




回答2:


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}
]);


来源:https://stackoverflow.com/questions/37031501/angular2-pathlocationstrategy-url-change-cause-page-reload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!