9

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
    Hard to tell without seeing what you're actually doing. How do you change the route? – Günter Zöchbauer May 04 '16 at 15:03
  • I change it manually in the browser's address bar. I.e. when I change `mysite/#/home` to `mysite/#/profile` using hash location strategy it changes the route, and does not reload a whole page; then when I switch my app's location strategy to PathLocationStrategy and try to change `mysite/home` to `mysite/profile` it does an unwanted page refresh. – Dominykas Dukštas May 04 '16 at 15:12
  • I updated my question accordingly, to be more specific – Dominykas Dukštas May 04 '16 at 15:16

2 Answers2

4

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.

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
4

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}
]);
Asaf
  • 1,790
  • 2
  • 12
  • 9
  • 2
    This is actually the right answer, loads beautifully! – jemiloii Apr 25 '17 at 20:59
  • 6
    @jemiloii That's not answering the question. Using routerLink works if the user clicks on those links, but if the user changes the address in the address-bar from `my-page` to `my-other-page` and presses Enter, the page will still reload – Drenai Dec 10 '17 at 21:02