In this tutorial, I'll go through using a simple service to check the previous route url from anywhere in your Angular 5 application.
The Service
The concept of this service is very simple. Basically, it saves the current url, then, when a NavigationEnd event fires, it saves that url in a variable previousUrl
, to be retrieved in your component.
Create a new service PreviousRouteService
. If you're using the Angular CLI, use the command ng generate service previous-route
. Make sure to add it to the providers
array in your app.module
file!
Here is the code:
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;
}
}
Using it in your component
To access the previous route url in a component, start by importing the service:
import { PreviousRouteService } from '../services/previous-route.service';
Inject it into the constructor like this:
constructor(
private previousRouteService: PreviousRouteService
) {}
Finally, access the previous url with this.previousRouteService.getPreviousUrl()
.
e.g.
ngOnInit() {
console.log(this.previousRouteService.getPreviousUrl());
}