How to determine previous page URL in Angular?

Chandra Shekhar picture Chandra Shekhar · Dec 8, 2016 · Viewed 157.9k times · Source

Suppose I am currently on the page which has the URL /user/:id . Now from this page I navigate to next page :id/posts.

Now Is there a way, so that i can check what is the previous URL, i.e. /user/:id.

Below are my routes

export const routes: Routes = [
  { 
    path: 'user/:id', component: UserProfileComponent
  },
  {  
    path: ':id/posts', component: UserPostsComponet 
  }
];

Answer

BYUNGJU JIN picture BYUNGJU JIN · Dec 19, 2017

Maybe all other answers are for angular 2.X.

Now it doesn't work for angular 5.X. I'm working with it.

with only NavigationEnd, you can not get previous url.

because Router works from "NavigationStart", "RoutesRecognized",..., to "NavigationEnd".

You can check with

    router.events.forEach((event) => {
  console.log(event);
});

But still you can not get previous url even with "NavigationStart".

Now you need to use pairwise.

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/pairwise';

constructor(private router: Router) {
  this.router.events
    .filter(e => e instanceof RoutesRecognized)
    .pairwise()
    .subscribe((event: any[]) => {
      console.log(event[0].urlAfterRedirects);
    });
}
    

With pairwise, You can see what url is from and to.

"RoutesRecognized" is the changing step from origin to target url.

so filter it and get previous url from it.

Last but not least,

put this code in parent component or higher (ex, app.component.ts)

because this code fires after finish routing.

Update angular 6+

The events.filter gives error because filter is not part of events, so change the code to

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

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);
});