How to access the previous route in your Angular app
shivlal kumavat
Posted on January 25, 2021
The blog is all about access the previous route
in your Angular app. In a simple way this service work like:
it saves the current
url
, after that, when aNavigationEnd
event fires.it saves that
url
in a variablepreviousUrl
, to be get in your component.
First create a new service PreviousRouteService
. If you're using the Angular CLI
, use the command ng generate service previous-route
and add in your app.module
file.
Your service file will look like below:
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Injectable()
export class PreviousRouteService {
private previousUrl: string;
private currentUrl: string;
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;
}
}
You can use in your component like below:
To use the previous route url
in your component, first importing the service:
import { PreviousRouteService } from '../services/previous-route.service';
Inject it into the constructor like below:
constructor(
private previousRouteService: PreviousRouteService
) {}
Now you can access the previous url with this.previousRouteService.getPreviousUrl()
.
ngOnInit() {
console.log(this.previousRouteService.getPreviousUrl());
}
Thank you for reading if any suggestion please comment below!!!
Happy Coding!!!
Posted on January 25, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.