I have developed a unique service that allows me to store route changes efficiently.
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Injectable()
export class RouteState {
private previousRoute: string;
private currentRoute: string;
constructor(private router: Router) {
this.currentRoute = this.router.url;
router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.previousRoute = this.currentRoute;
this.currentRoute = event.url;
};
});
}
public getPreviousRoute() {
return this.previousRoute;
}
}
However, I am facing an issue where the currentRoute and previousRoute variables become undefined every time there is a route change. Can anyone suggest a solution?