Angular 6 – getting previous url from angular router
August 7, 2018
Below is a service that can be used to get the previous url from angular router where it is navigated via router or browser’s back button
// 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;
}
}
Usage in component
constructor(
private routerService: RouterExtService
) {}
// referrer can be get from the service
const referrer = this.routerService.getPreviousUrl();
