How to determine previous page URL in Angular?
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
}
];
Solution 1:
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);
});
Solution 2:
You can subscribe to route changes and store the current event so you can use it when the next happens
previousUrl: string;
constructor(router: Router) {
router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
console.log('prev:', event.url);
this.previousUrl = event.url;
});
}
See also How to detect a route change in Angular?
Solution 3:
Create a injectable service:
import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';
/** A router wrapper, adding extra functions. */
@Injectable()
export class RouterExtService {
private previousUrl: string = undefined;
private currentUrl: string = undefined;
constructor(private router : Router) {
this.currentUrl = this.router.url;
router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.previousUrl = this.currentUrl;
this.currentUrl = event.url;
};
});
}
public getPreviousUrl(){
return this.previousUrl;
}
}
Then use it everywhere you need. To store the current variable as soon as possible, it's necessary to use the service in the AppModule.
// AppModule
export class AppModule {
constructor(private routerExtService: RouterExtService){}
//...
}
// Using in SomeComponent
export class SomeComponent implements OnInit {
constructor(private routerExtService: RouterExtService, private location: Location) { }
public back(): void {
this.location.back();
}
//Strange name, but it makes sense. Behind the scenes, we are pushing to history the previous url
public goToPrevious(): void {
let previous = this.routerExtService.getPreviousUrl();
if(previous)
this.routerExtService.router.navigateByUrl(previous);
}
//...
}