Location Service In Angular
To interact with the browser URL, the Angular Location service is used. It can be used to keep track of URL changes. It can be used to read the current URL, edit it, traverse back and forth in the browser history, and so on. In this article, we will learn how to use the Angular Location service. We will learn how to use location.back(), location.forward(), location.path(), location.go(), location.replacestate(), location.getState(), location.onUrlChange(), and other location-related functions.
To browse to different portions of the application, we commonly using Angular Router. The location service does not allow us to navigate, but it does allow us to change the URL. It fully bypasses the Angular Router.
How to use Location Service
The @angular/common package includes the Location service. As a result, import it into the Component that you wish to use.
import { Location } from '@angular/common';
Finally, inject it into the component you wish to use it in.
export class MyComponent { constructor(private location: Location) { } }
Going back and forward
back()
goBack() { this.location.back(); }
forward()
goForward() { this.location.forward(); }
Get the current path
path()
getPath() { return this.location.path(); }
Manipulate the URL
go()
go(path: string, query: string = '', state: any = null): void
Example:
location.go("/product/1");
replaceState()
replaceState(path: string, query: string = '', state: any = null): void
Examples:
location.replaceState():
Get History State Object
getState()
location.getState():
- By using routerLink directive.
- By using the router.navigateByUrl() method.
- via location.go() method of the location service
- via location.replaceState() method of the location service
<a [routerLink]="['dynamic']" [state]="{ id:1 , name:'Angular'}">Dynamic Data</a>
this.router.navigateByUrl('/dynamic', { state: { id:1 , name:'Angular' } }); location.go("/product/1","", { id:1 , name:'Angular'}) location.replaceState("/product/1","", { id:1 , name:'Angular'})
Listen to URL Changes
onUrlChange()
onUrlChange(fn: (url: string, state: unknown) => void) ngOnInit() { this.location.onUrlChange( (url: string, state: unknown) => { console.log("Location changes to "+url); console.log(state); }) }
Subscribe to the platform’s popState events.
- On the browser window location, the user hits the Back/Forward button.
- location.forward() and location.back() are two functions that can be used together.
- The functions location.go() and location.replaceState() are employed.
subscribe(onNext: (value: PopStateEvent) => void, onThrow?: (exception: any) => void, onReturn?: () => void): SubscriptionLike this.location.subscribe( ( (value:PopStateEvent) => { console.log("locaton OnNext") console.log(value); }), ( ex => { console.log("Error occured postate event") console.log(ex); }) )