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.


Scope

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:

  • Create a simple root-scope service called PreviousRouteService
  • Leverage Router events to track and capture previous and current route information

Service

First, I created a simple Angular service scoped at the root level of my application. Then, I imported Router and added properties and a gettermethod 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

Previous Routes in Angular 6+
1.70 GEEK