Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular using # in URLS

Tags:

url

angular

ietf

I'm currently working on a URL parser that formats and corrects relative links. I designate some characters to be special and included is "#".

I found that this becomes an issue when I'm processing pages that are developed with Angular, because makes use of #'s in the URL. However, in reading up on the IETF protocol for URL naming, it seems like #'s are reserved characters.

Can someone explain to me how Angular interacts with URL naming?

like image 460
labiblioteca4 Avatar asked Sep 28 '18 23:09

labiblioteca4


1 Answers

Routing strategy

When configuring application routing in an angular project one can choose between regular HTML5 routing (PathLocationStrategy) or "hash-style URL" routing (HashLocationStrategy).

The default is PathLocationStrategy but hash-style routes can be implemented by passing {useHash: true} as the second parameter to the RouterModule.forRoot() function

According to Angular's official documentation regarding LocationStrategy and browser URL styles:

Older browsers send page requests to the server when the location URL changes unless the change occurs after a "#" (called the "hash"). Routers can take advantage of this exception by composing in-application route URLs with hashes.

Why does Angular support hash routes

A # in a URL represents an anchor identifier (RFC1738) and is very useful when linking to specific content within a page.

What angular exploits with the HashLocationStrategy is the fact that any content after the # symbol isn't send to a server - which makes it ideal to use it for storing application state.

Why is it useful

With hash routes a page reload (or revisit through bookmark) on a subpage like

http://localhost:4200/#/articles/35

doesn't query the server for the subpage, but instead returns the main application page

http://localhost:4200/

This way the server implementation only needs to know about the root page (which is the only thing that'll ever be queried)

Using the PathLocationStrategy (default) the server needs to be set up to handle requests for every single URL your application implements.

like image 55
Daniel Avatar answered Oct 18 '22 11:10

Daniel