What Is PathLocationStrategy?
This is the default strategy in Angular so we need to do nothing to enable it.
It takes advantage of a relatively new HTML5 API called
pushstate
(from the HTML5 history API).
By using
pushstate
we can change the URL and not have the browser request the page from the server and without needing to use a hash fragment.
localhost:4040/search
By using the
pushstate
API we can change the URL to
localhost:4040/artist/1234/tracks
And the browser won’t make a GET request to the server for
/artist/1234/tracks
That sounds perfect for client side routing right?
- We get a URL that looks just like any other URL so can be bookmarked, shared and so on.
- The browser doesn’t send the request to the server so the routing is handled on the client side.
Unfortunately it has one big downside, if we then reloaded the page or bookmarked and opened it later the browser would make a request to the server for e.g.
localhost:4040/artist/1234/tracks
By using a hash fragment the server never needs to know about any application URL, it will only ever get asked for the root page and it will only ever return the root page.
But by using a
PathLocationStrategy
the server needs to be able to return the main application code for every URL, not just the root URL.
So with co-operate with a server side that supports this functionality, it’s possible and quite easy to implement a server side like this but it does require some effort and cooperation.
PathLocationStrategy
we need to
A
LocationStrategy
used to configure the Location
service to represent its state in thepath of the browser's URL.class PathLocationStrategy extends LocationStrategy {
onPopState(fn: LocationChangeListener): void
getBaseHref(): string
prepareExternalUrl(internal: string): string
path(includeHash: boolean = false): string
pushState(state: any, title: string, url: string, queryParams: string)
replaceState(state: any, title: string, url: string, queryParams: string)
forward(): void
back(): void
// inherited from common/LocationStrategy
abstract path(includeHash?: boolean): string
abstract prepareExternalUrl(internal: string): string
abstract pushState(state: any, title: string, url: string, queryParams: string): void
abstract replaceState(state: any, title: string, url: string, queryParams: string): void
abstract forward(): void
abstract back(): void
abstract onPopState(fn: LocationChangeListener): void
abstract getBaseHref(): string
}
0 comments:
Post a Comment