Location Strategy In Angular

Location Strategy In Angular

In this article, we will learn about the Location Strategy (Angular Routing Strategy) that the Angular routing module supports. PathlocationStrategy and HashLocationStrategy are supported by Angular. We'll go through what client-side routing is and how it functions. We look at how hash-style HTML5 routing works and the benefits and drawbacks of each. Finally, we'll look at how to use the PathLocationStrategy (HTML5 routing) HashLocationStrategy to create an Angular application. (Routing in the hash style).

Location Strategies in Angular Router

Because Angular applications are Single Page Applications, they should not communicate the URL to the server or reload the page every time the user requests a new page.

In Angular Apps, URLs are entirely local. The Angular router goes to the new component and renders its template, as well as updates the view's history and URL. All of this takes place in the browser on a local level.

Angular accomplishes this in one of two ways. Location Strategies are what they're called.

Our URL/Request is resolved using the Location Strategy. It also impacts the appearance of your URL.

Two Location Strategies are supported by Angular:

    1. HashLocationStrategy

        http://localhost:4200/#/product is an example of a URL.

    2. PathLocationStrategy

        http://localhost:4200/product is an example of a URL.

Before we go any further, let's define what client-side routing is.

Client-Side Routing

In a multi-page web application, the application must send a request to the web server every time it needs to display a page. You can do so by putting the URL into the address box or by selecting the Menu link/button. Each of these actions causes the browser to send a new request to the Web server.

Angular Applications, on the other hand, are single-page applications, or SPAs.

On a single page, all of the components are displayed.

The single HTML page is loaded when the Web application is loaded in a typical single page application. Only a portion of the page is dynamically modified as the user interacts with it.

You can see the following if you open the index.html in any of the angular applications.

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

The placeholder (selector) "app-root" is declared in the root component.

Within the "app-root" Angular builds and loads the view associated with the root component. Within the "app-root" selector, any subsequent components are also dynamically loaded.

All of this is handled by Angular in the background.

We are not needed to update the URL in this case. However, there are a few drawbacks to this.
  • The page will not be able to be refreshed.
  • You won't be able to access a certain view by inputting its URL.
  • It is not possible to share the URL with someone else.
  • Because you can't navigate back to the previous page, the Back button won't work.
  • SEO is not a viable option.

This is where client-side routing enters the picture.

By conducting the procedure in the browser, client-side routing replicates server-side routing. It updates the browser history and changes the URL in the address bar without actually sending the request to the server.

How Client-Side Routing works

There are two approaches to handling client-side routing.
  1. Hash style Routing
  2. HTML 5 Routing

Hash Style Routing

The anchor tags technique is used to achieve client-side routing in the Hash style routing.

When the anchor tags are used with the #, we can leap to a specific location on the web page.

As an example,

Index.html

<a name="contact">Contact Us</a>

If we went to http://mysite.com/index.html#contact, the browser would scroll to the Contact us label's location.

The browser does not send the request to the Web server if the required anchor tag is on the current page.

This approach is used to build the URL in Hashstyle Routing.

The URL would be something like this:

http://www.example.com
http://www.example.com/#/about
http://www.example.com/#/contact

Only http://www.example.com is sent to the server in all of the preceding examples. "#/about" and "#/contact" URLs are never delivered to the server.

HTML 5 routing

With the advent of HTML5, browsers can now use the history object to programmatically change the browser's history.

We can now programmatically add browser history entries and change the location without generating a server page request by using the history.pushState() method.

The following three parameters are accepted by the history.pushState method.
  1. State object: A state object is a JavaScript object that is linked to the newly formed history entry via pushState()
  2. Title: This is a state title that can be chosen.
  3. URL: The URL of the new history entry. The browser will not take you to that page.

As an example,

var stateObj= { message: "some message" };
history.pushState(stateObj, "title", newUrl);

Using the history.push command The browser creates new history entries that update the displayed URL without requiring a new request, as stated in the method.

Example

The server transmits the index.html file when you request http://www.example.com.

Angular now uses the history when you click on the ProductList link.

To push the state and update the URL to http://www.example.com/ProductList, use the pushState function.

We now use the historical method to push the state and change the URL to 

http://www.example.com/product/1 when you click on a certain Product.

When you click the back button, the browser retrieves and displays the

http://www.example.com/ProductList URL from your history.

However, there are certain drawbacks to this strategy.
  1. HTML 5 isn't supported by all browsers.
  2. HTML5 is not supported by the older browser. As a result, if you want to support older browsers, you must use the hash style of routing.
  3. HTML5-based routing necessitates server support.

Why Server Support Needed for HTML 5 routing

Take a look at the sample above.

What happens if you type http://www.example.com/ProductList into your browser and hit the refresh button?

The request will be sent to the web server by the browser. The 404 (page not found) error will be returned because the page ProductList does not exist.

If we can redirect all requests to index.html, we may be able to solve this problem.

When you request something from http://www.example.com/ProductList, the Web server must redirect you to index.html and then return the request. Angular will then read the URL in the front-end and dynamically load the ProductListComponent.

To make HTML5 routing function, you must tell the webserver to serve /index.html for all incoming requests, regardless of their path.

Location Strategy

As previously stated, Angular supports both Hashstyle and HTML 5 Routing. Hashstyle routing is implemented by HashLocationstrategy, and HTML5 style routing is implemented by Pathlocationstrategy.

PathLocationStrategy Vs HashLocationStrategy

PathLocationStrategy

Pros:
  • Creates a simple URL, such as http://example.com/foo.
  • Server-Side Rendering is supported.

Cons:
  • This feature is not available in older browsers.
  • For this to work, you'll need server support.

HashLocationStrategy

Pros:
  • All browsers support it.

Cons:
  • Creates a URL that looks like this: http://example.com/#foo
  • Server-Side Rendering is not supported.

PathLocationStrategy

In an Angular application, the PathLocationStrategy is the default approach.

To configure the strategy, we must include a <base href> in the <head> section of our application's main page (index.html).

<base href="/">

This element is used by the browser to create relative URLs for the document's static resources (images, CSS, and scripts).

If you don't have access to the index.html's <head> section, you can use one of the two methods below.

Add the APP_BASE_HREF value as indicated in the root module's provider's section.

import {Component, NgModule} from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';
 
@NgModule({
providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
})
class AppModule {}

Alternatively, for all static resources such as CSS, pictures, scripts, and HTML files, utilise the absolute path.

HashLocationStrategy

The HashLocationStrategy can be used by passing useHash: true in an object as the second parameter to RouterModule.forRoot in the AppModule.

@NgModule({
declarations: [
    AppComponent,HomeComponent,ContactComponent,ProductComponent,ErrorComponent
],
imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    Hashlocationstrategy RouterModule.forRoot(appRoutes, { useHash: true }
],
providers: [ProductService],
bootstrap: [AppComponent]
})

Which Location Strategy to Use

As a location strategy, we recommend using the HTML 5 style (PathLocationStrategy).

Because
  • It generates SEO-friendly URLs that are easier to understand and remember for users.
  • By drawing the pages on the server first and then delivering them to the client, you can take advantage of server-side rendering, which will help our application load faster.

Only use the hash location technique if you must support outdated browsers.

Conclusion

In this article, we learn, In Angular two alternative location strategies or routing strategies. PathlocationStrategy is one, and HashLocationStrategy is the other. PathlocationStrategy employs HTML 5 Routing, whereas HashLocationStrategy uses Hash style routing.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post