Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rajaramtt/e649e51f251f01ae9eeee6936370fe2d to your computer and use it in GitHub Desktop.
Save rajaramtt/e649e51f251f01ae9eeee6936370fe2d to your computer and use it in GitHub Desktop.
Know the difference between the HashLocationStrategy and PathLocationStrategy.

To enable HashLocationStrategy in an Angular application we pass {useHash: true} when we are providing our routes with RouterModule, like so:

TypeScript RouterModule.forRoot(routes, {useHash: true})

http://somedomain.com/page#routing-strategies Taking a look at the app we’ve built so far, if running locally the URLs look something like:

localhost:4040/#/search localhost:4040/#/artist/1234/tracks According to the the server there is only ever one URL localhost:4040, the other hash fragment stuff is ignored by the server.

This is why we call what we are building a Single Page Application, there is only ever one page requested from the server. In the above example it’s localhost:4040 — the other pages are just changes to the hash fragment which the client application deals with, from the perspective of the server the whole site is just a single page.

This is the default strategy in Angular so we need to do nothing to enable it.

It takes advantage of a relatively new HTML5 API called pushstate (from the HTML5 history API).

By using pushstate we can change the URL and not have the browser request the page from the server and without needing to use a hash fragment.

So if we were at

localhost:4040/search

But by using a PathLocationStrategy the server needs to be able to return the main application code for every URL, not just the root URL.

So with PathLocationStrategy we need to co-operate with a server side that supports this functionality, it’s possible and quite easy to implement a server side like this but it does require some effort and cooperation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment