Wednesday, 27 December 2017

Location Strategies in Angular Router

Angular Supports Pathlocation strategy and HashLocation Strategy. We will look at what is client side routing and how it works.


Location Strategies in Angular Router


Being a Single Page Application, the Angular applications should not the send the URL to the server and should not reload the page, every time user requests for a new page.

The URLs are strictly local in an Angular Apps. The Angular router navigates to the new component and renders its template and updates the history and URL for the view. All this happens locally in the browser.
There are two ways, by which Angular achieves this. These are called Location Strategies.
The Location Strategy defines how our URL/Request are resolved. It also determines how your URL will look like
Angular supports two Location Strategies:
  1. HashLocationStrategy
    Where URL looks like http://localhost:4200/#/product
  2. PathLocationStrategy
    Where URL looks like http://localhost:4200/#/product

Client Side Routing


In a Multi-page web application, Every time the application needs to a display a page it has to send a request to the web server. You can do that by either typing the URL in the address bar, clicking on the Menu link/ button. Every such action results in a new request being sent to the Web server

But, the Application built using the Angular 2 are single page applications or SPA.
All the components are displayed on a single page
In a Typical Single Page Application, when the Web application is loaded it loads the single HTML page. Whenever the user interacts with the page, only a part of the page is dynamically updated.
If you open the index.html in any of the angular 2 application you would see the following HTML markup



<body>
<app-root>Loading...</app-root>
</body>


The “app-root” is a placeholder (selector), which is defined in the root component.

Angular 2 generates and loads the view associated with the root component inside the “app-root”. Any subsequent components are also loaded dynamically inside the “app-root” selector

Angular does all this behind the scenes.
In such scenario, we are not required to change the URL. But that brings few cons
  • You won’t be able to refresh the page
  • You won’t be able to go to a particular view by typing the URL
  • You won’t be able to share the URL with someone
  • You can not use the Back button to go back to the previous page
  • SEO is not possible
That is where the client-side routing comes into the picture.
The Client-side routing simply mimics server-side routing by running the process in the browser. It changes the URL in the browser address bar and updates the browser history, without actually sending the request to the server.

How Client-Side Routing works

The Client side routing is routing is handled in two ways
  1. Hashstyle Routing
  2. HTML 5 Routing

Hashstyle Routing

The Hash style routing using the anchor tags technique to achieve client side routing.
The anchor tags, when used along with the # allows us to jump to a place, within the web page.
For Example
Index.html
And we visited the URL http://mysite.com/index.html#contact, the browser would scroll to the location of the Contact us label
When the requested anchor tag is on the current page, then the browser does not send the request to the Web server.
The Hashstyle Routing uses this technique to create the URL
The URL would look like something like
http://www.example.com
http://www.example.com/#/about
http://www.example.com/#/contact
In the above example, the URL’s  “#/about” and “#/contact” is never sent to the server

HTML 5 routing

The introduction of HTML5, now allows browsers to programmatically alter the browser’s history through the history object.
Using the history.pushState() method, we can now programmatically add the browser history entries and change the location without triggering a server page request.
The history.pushState method accepts the following three parameters.
  1. State object: A state object is a JavaScript object which is associated with the new history entry created by pushState()
  2. Title: This is optional title for the state
  3. URL: The new history entry’s URL. The browser won’t jump to that page.
For example
Using the history.pushState method, The browser creates new history entries that change the displayed URL without the need for a new request.
Example
When you request for http://www.example.com the server sends the index.html
Now, When you click on a ProductList link, Angular use’s the history.pushState method to push the state and change the URL to http://www.example.com/ProductList
Now, when you click on the specific Product, we again the use history method to push the state and change the URL to http://www.example.com/product/1
Here, when you click the back button, the browser will retrieve the http://www.example.com/ProductList from the history and displays it.
But there are cons to this approach
  1. Not all browsers support HTML 5
  2. The older browser does not support HTML5. So if you want to support older browser, you have to stick to the hashstyle routing
  3. The server support is needed for HTML5 based routing.

Why Server Support Needed for HTML 5 routing

Now, consider the above example
What would happen, when you type the URL http://www.example.com/ProductList and hit the refresh button
The browser will send the request to the web server. Since the page ProductList does not exist, it will return the 404 (page not found) error.
This problem could be solved, if we are able to redirect all the request to the index.html
It means that when you ask from http://www.example.com/ProductList, the Web server must redirect it to index.html and return the request. Then in the Front-end Angular will read the URL and dynamically load the ProductList component.
To make HTML5 routing work you need to send the instruction to the web server to serve /index.html for any incoming request, no matter what the path is.

Location Strategy

As mentioned earlier, Angular implements both Hashstyle & HTML 5 Routing. HashLocationstrategy implements the Hashstyle routing & Pathlocationstrategy implements the HTML5 style routing

PathLocationStrategy Vs HashLocationStrategy

PathLocationStrategy

Pros:
  • Produces a clear URL like http://example.com/foo
  • Supports Server-Side Rendering
    Server-side Rendering is a technique that renders critical pages on the server that can greatly improve perceived responsiveness when the app first loads
Cons:
  • Older browser does not support
  • Server Support needed for this to work

HashLocationStrategy

Pros:
  • Supported by all browsers
Cons:
  • Produces a URL like http://example.com/#foo
  • Will not Support Server-Side Rendering

Using the PathLocationStrategy

The PathLocationStrategy is the default strategy in Angular 2 application.
To Configure the strategy, we need to add <base href> in the <head> section of root page (index.html) of our application
The Browser uses this element to construct the relative URLs for static resources (images, CSS, scripts) contained in the document.
If you do not have access to <head> Section of the index.html., then you can follow either of the two steps
Add the APP_BASE_HREF value.as follows in the providers section of the root module
or use the absolute path for all the static resources like CSS, images, scripts, and HTML files.

Using the HashLocationStrategy

You can use the HashLocationStrategy by providing the useHash: true in an object as the second argument of the RouterModule.forRoot in the AppModule.

Which Location Strategy to Use

It is recommended to use the HTML 5 style as your location strategy
Because
  • It produces the clean and SEO Friendly URLs that are easier for users to understand and remember.
  • You can take advantage of the server-side rendering, which will make our application load faster, by rendering the pages in the server first before delivering it the client
Use hashlocationstrtegy only if you have to support the older browsers.

Location Strategies in Angular Router

Angular Supports  Pathlocation strategy  and  HashLocation Strategy . We will look at what is client side routing and how it works. Loc...