Location Service In Angular

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()

To return to the previous URL, use location.back().

goBack() {
  this.location.back();
}

forward()

To get to the next URL, use location.forward().

goForward() {
  this.location.forward();
}

Get the current path

path()

The location.path function can be used to get the current URL path ()

getPath() {
  return this.location.path();  
}

Manipulate the URL

go()

To change the current URL to a new one, call location.go(). The new URL is also added to the browser's history. The new URL is not navigated by location.go(). You must utilise the Angular router to browse to the new URL.

Syntax:
go(path: string, query: string = '', state: any = null): void

Example:
location.go("/product/1");

It's worth noting that you can also alter the URL's status object.

replaceState()

Make use of the place. To change the current URL to a new one, use replaceState(). It takes the place of the most recent item in the browser history.

With one exception, this is fairly identical to location.go(). The URL is added to the browser history by location.go(), and the top item in the history is replaced by the newly added one by location.replaceState().

Syntax:
replaceState(path: string, query: string = '', state: any = null): void

Examples:
location.replaceState(): 

Get History State Object

getState()

location.getState(): 

The preceding, which was introduced in Angular 8, returns the current value of the state object. This method can be used to pass dynamic data through Angular Routes.

The state object can be passed in the following ways.
  1. By using routerLink directive.
  2. By using the router.navigateByUrl() method.
  3. via location.go() method of the location service
  4. 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()

Listen for changes in URLs using onUrlChange. This API can be used to track changes made by the Angular framework. Neither "popstate" nor "hashchange" events can detect these.

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.


Subscribe to the location service to hear popState events from the platform.

When the popState events are triggered,
  1. On the browser window location, the user hits the Back/Forward button.
  2. location.forward() and location.back() are two functions that can be used together.

Not to mention not being fired.
  1. 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);
  })
)

Conclusion

To modify routes, it's recommended to use the Router service. Only use Location Services if you need to manipulate the Router without refreshing the page.

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