Angular features the powerful and versatile Router. Recently, I had a need to ensure that my components could access information about the previous route a user visited inside my application. To my surprise, Router doesn’t support such functionality out of the box as of today. But it still provides the necessary enablers to build this functionality quickly.
My use case assumed that I only needed to access the previous route inside of my ngOnInit()
lifecycle hook of various components and that I had no requirement to keep information persistent through page reloads. So I decided to:
PreviousRouteService
First, I created a simple Angular service scoped at the root level of my application. Then, I imported Router and added properties and a getter
method for the previousUrl
. Then, I subscribed to all Router events to see what was happening during route changes:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({
providedIn: "root"
})
export class PreviousRouteService {
private previousUrl: string;
private currentUrl: string;
constructor(private router: Router) {
this.currentUrl = this.router.url;
this.previousUrl = null;
this.router.events
.subscribe((events) => {
console.log(events)
});
}
public getPreviousUrl() {
return this.previousUrl;
}
};
#ionic #angular #typescript #javascript #programming