NashTech Insights

Angular Location Service: go/back/forward

Alka Vats
Alka Vats
Table of Contents
angular

Introduction:

The Angular Location service is used to interact with the browser URL. We can use it to track the URL changes. Use it to read the current URL, modify the URL, go back or forward through the browser history, etc. In this blog, we will look at how to make use of the Angular Location service. We learn how to make use of location.back(), location.forward(), location.path(), location.go(), location.replacestate(), location.getState(), location.onUrlChange() etc

We usually make use of Angular Router to navigate to different parts of the application. The location service does not perform navigation but allows us to manipulate the URL. It bypasses the Angular Router completely. If you want to learn about a new feature of angular, you can refer here.

How to use Location Service

The Location service is part of the @angular/common package. Hence import it into the Component, where you want to use it.

import { Location } from '@angular/common';

And finally, inject it into the component, where you want to use it

export class MyComponent {
  constructor(private location: Location) { 
  }
}

Going back and forward

back()

Use location.back() to go back to the previous URL.

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

Use location.forward() to go to the next URL.

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

Get the current path

path()

The current URL path can be obtained using the location.path()

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

Manipulate the URL

go()

Use the location.go() to change the current URL to a new given URL. It also pushes the new URL into the browser history. The location.go() does not navigate to the new URL. To navigate to the new URL, you must use the Angular router

Syntax:
go(path: string, query: string = '', state: any = null): void
location.go("/product/1");

Note that, you can also change the state object of the URL.

replaceState()

Use the location.replaceState() to change the current URL to a new given URL. It replaces the top item in the browser history.

This is very similar to location.go() one difference. The location.go() add the URL to the browser history, while location.replaceState() replacing the top item in the history with the newly added one

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

Get History State Object

getState()
location.getState(): 

The above introduced in Angular 8, returns the current value of history. state object. You can use this method to pass the dynamic data via the Angular Routes

You can pass the state object by using 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()

Use onUrlChange to listen for a change in URLs. This API can be used to catch updates performed by the Angular framework. These are not detectable through “popstate” or “hashchange” events.

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 listen to the platform’s popState events

The popState events are fired when

  1. The user clicks on the Back/Forward button on the browser window
  2. location.forward() & location.back() is called.

And not fired when

Location.go() and location.replaceState() is used.

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

It’s better to use the Router service to trigger route changes. Use Location Services, only when you need to manipulate the Router, without resulting in a page refresh.

Finally, for more such posts, please follow our LinkedIn page- FrontEnd Competency.

Alka Vats

Alka Vats

Alka Vats is a Software Consultant at Nashtech. She is passionate about web development. She is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. She is a quick learner & curious to learn new technologies. Her hobbies include reading books, watching movies, and traveling.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: