Routing strategies

There are two client-side routing strategies in Angular:

  • HashLocationStrategy (typically used for client-side purposes, such as anchor tags)
  • PathLocationStrategy (this is the default)

To enable HashLocationStrategy, in the app.module.ts file, where we have RouterModule.forRoot(appRoutes), append { useHash: true } as the second parameter in the forRoot method. This is what it should look like:

RouterModule.forRoot(appRoutes, { useHash: true })

URLs with HashLocationStrategy have a hash sign (#) in their path. Here is an example:

http://madeuplistofpeople.com/superheros#cloudman

The preceding URL represents a get request to http://madeuplistofpeople.com/superheros to the server.

Everything from the hash onward is not part of the request, because the browser only sends everything in the browser's location bar, to the left of the hash sign, to the server.

The #cloudman portion of the URL is used exclusively by the client, and, typically, this is used by the browser to automatically scroll down to the anchor tag on the page (in this case, to the anchor tag with a name attribute of cloudman).

One use of the HashLocationStrategy strategy is for using the hash sign to store application state, which is convenient for implementing client-side routing for an SPA.

As an example, consider the following URLs:

This URL pattern is great for an SPA because the only request going to the server is http://madeuplistofpeople.comwhich is essentially one page. The client side will handle the different hash fragments (that is, from the hash sign to the end of the right-hand side of the hash sign) in whichever way it was programmed to.

To wrap up this section, an important concept of PathLocationStrategy is that Angular takes advantage of an HTML5 history API called pushstate. We can change the URL using the pushstate API while suppressing the traditional default action by the browser to send the new request (that is, the altered URL) to the server. This makes it possible to implement client-side routing without resorting to using a hash sign (#). This is why it is the default client-side routing strategy in Angular.

However, there is a downside. If the browser were to be refreshed, a request would be made to the serverwhich would reset your application with whatever the server sent back. In other words, your application would lose its stateunless you had implemented local storage strategies.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.60