Categories
Angular Answers

How to determine previous page URL in Angular?

Spread the love

Sometimes, we want to determine previous page URL in Angular.

In this article, we’ll look at how to determine previous page URL in Angular.

How to determine previous page URL in Angular?

To determine previous page URL in Angular, we can listen for navigation events.

For instance, we write

import { filter, pairwise } from "rxjs/operators";

to import the filter and pairwise operator functions.

Then we write

this.router.events
  .pipe(
    filter((evt: any) => evt instanceof RoutesRecognized),
    pairwise()
  )
  .subscribe((events: RoutesRecognized[]) => {
    console.log("previous url", events[0].urlAfterRedirects);
    console.log("current url", events[1].urlAfterRedirects);
  });

to call this.router.events.pipe to return events that are instance of the RoutesRecognized class.

We call pairwise to return the current and previous navigation events.

Then we call subscribe with a callback to get both events’ objects and get the URL with urlAfterRedirects.

Conclusion

To determine previous page URL in Angular, we can listen for navigation events.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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