Tuesday, September 15, 2020

Location Strategies in Angular Routing

In Angular routing we have two location strategies that we can use to implement client side routing.

  1. PathLocationStrategy
  2. HashLocationStrategy

In this post we’ll see what is location strategy, which routing strategy to chose for your SPA and what are the differences between the HashLocationStrategy and PathLocationStrategy.


Location strategy in Angular

In Angular apps which are Single Page Applications (SPA), URLs are strictly local which means browser won't send this URL to the server and will not reload the page for each request.

When the Angular router navigates to a new component view, it updates the browser's location and history with a URL for that view. How to update the URL as per the new browser location can be done in two ways in Angular and this process is known as location strategy.

Location strategy determines how route URL is composed and how it is parsed to determine new path. In Angular there are two LocationStrategy providers-

1. HashLocationStrategy- Uses the anchor tag (a hash '#') as the client-side URL http://localhost:4200/#/account

2. PathLocationStrategy- No need for anchor tag trick, a "natural" URL is used. http://localhost:4200/account

Client side routing strategy

With client side routing we’re not sending a request to the server on every URL change. Server only gives us a single page and it’s our JavaScript that renders the different pages. Based on two location strategies there are two corresponding routing strategies.

  1. Hash based routing
  2. HTML5 routing

Hash based routing

In a web page when we link to an anchor like this-

<a name="clientside"><h3>Client Side</h3></a>

and then visit the URL http://example.com/client.html#clientside the browser jumps directly to that <h3> tag within the web page without making a new request to the server.

Older browsers send page requests to the server when the location URL changes unless the change occurs after a "#". Hash based client side routing took advantage of this exception by composing route URLs with hashes. Here are some examples of hash URLs.

http://example.com/#/about
http://example.com/#/account

Since any thing after the # in the URL is not sent to the server so server only renders the http://example.com request any addition to that URL in the form of hash fragments like #/about and #/account are not sent to the server but resolved locally by client side routing.

How to configure HashLocationStrategy

If you want to use HashLocationStrategy then you have to pass useHash: true in an object as the second argument of the RouterModule.forRoot() in the AppModule.

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(routes, { useHash: true }) 
  ],
  ....
  ....
})
export class AppModule { }

Another way is to pass HashLocationStrategy as value of useClass property.

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(routes, { useHash: true }) 
  ],
  ....
  providers: [
   { provide: LocationStrategy, useClass: HashLocationStrategy }
  ],
  ....
})
export class AppModule { }

HTML5 routing

Modern HTML5 browsers have the ability to programmatically create new browser history entries that changes the browser's URL without triggering a server page request. That is done using history.pushState() method that can change browser's location and history without triggering a server page request.

Using history object you can move backward and forward through the user's history using the back() and forward() methods.

With HTML5 routing when base URL (http://example.com) is used then the request is sent to the server. If you make a further request like http://example.com/account then the Angular pushes the state using history.pushState() to make a new history entry and changes the URL locally and renders it. If you make a further request for a specific account like http://example.com/account/A1001 then a new history entry is created for the new URL and it is rendered.

You also have the ability to move back and forward by retrieving the entries from the history object. Clicking back will take you back to http://example.com/account URL and from there clicking forward will bring you back to http://example.com/account/A1001

How to configure PathLocationStrategy

PathLocationStrategy is the default strategy in Angular.

For PathLocationStrategy to work properly you must add a <base href> element to the app's index.html. <base href> element specifies the base URL to use for all relative URLs. If you are referencing CSS files, scripts, and image, path to those resources is created by prefixing base URL.

You can add <base href> in the <head> section of root page (index.html) of your application

<base href="/">

If you don't have access to <head> or the index.html and can't add the <base> element then you can take the following two steps in order to use HTML5 URLs-

1. Provide the router with an appropriate APP_BASE_HREF value.

@NgModule({
providers: [{provide: APP_BASE_HREF, useValue: '/'}]
})
class AppModule {}

2. Use root URLs (absolute path) for all web resources: CSS, images, scripts, and template HTML files.

Which Routing Strategy should be used

Almost all Angular projects should use the default HTML5 style as you get the following benefits-

  1. It produces URLs that are easier for users to understand.
  2. Since the URL is same as what is used for server requests so you also have an option to do server-side rendering if required.

You will still be required to use Hash based routing in the following scenarios-

  1. If you need to support older browsers that don’t support HTML5 mode routing.
  2. The server you are using doesn’t support HTML5 based routing.

Reference: https://angular.io/guide/router#locationstrategy-and-browser-url-styles

That's all for this topic Location Strategies in Angular Routing. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. CanDeactivate Guard in Angular With Example
  2. Angular Route Resolver - Passing Data Dynamically
  3. Angular Route - Passing Static Data
  4. Setting Wild Card Route in Angular
  5. Using RouterLinkActiveOptions to Fix Link Highlighted Problem

You may also like-

  1. Angular ngSwitch Directive With Examples
  2. Angular Disable Button Example
  3. How to Create a Custom Observable in Angular
  4. Angular Custom Two-Way Data Binding
  5. Reduction Operations in Java Stream API
  6. How to Loop Through HashSet in Java
  7. Global Keyword in Python With Examples
  8. Spring JdbcTemplate Insert, Update And Delete Example

No comments:

Post a Comment