Get previous route Angular 7 Get previous route Angular 7 typescript typescript

Get previous route Angular 7


Use angular's Location service, it is inbuilt to angular and import it from '@angular/common' like this:

import { Component, OnInit, Input } from '@angular/core';import { ActivatedRoute } from '@angular/router';import { Location } from '@angular/common';import { Hero }         from '../hero';import { HeroService }  from '../hero.service';@Component({  selector: 'app-hero-detail',  templateUrl: './hero-detail.component.html',  styleUrls: [ './hero-detail.component.css' ]})export class HeroDetailComponent implements OnInit {  @Input() hero: Hero;  constructor(    private location: Location  ) {}  goBack() {    this.location.back();  }   }

And then use location.back() to goto previous page. This is a working example:

https://stackblitz.com/angular/qvvrbgrmmda


If you just want the previous route you can create an observable like this

 get previousRoute$(): Observable<string> {    return this.router.events.pipe(      filter(e => e instanceof RoutesRecognized),      pairwise(),      map((e: [RoutesRecognized, RoutesRecognized]) => e[0].url)    );  }

Now you can subscribe this observable and perform any action (Make sure you unsubscribe this observable on OnDestroy event.)

this.previousRoute$.subscribe(url => {  //perform your action});

NOTE: This observable will start emitting event when user is on 2nd navigation.


Here is a way to get you previous route using @angular/router

Find more on the original post

import { Injectable } from '@angular/core';import { Router, RouterEvent, NavigationEnd } from '@angular/router';import { filter } from 'rxjs/operators';@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                    .pipe(filter((event: RouterEvent) => event instanceof NavigationEnd))                    .subscribe((event: NavigationEnd) => {                        this.previousUrl = this.currentUrl;                        this.currentUrl = event.urlAfterRedirects;                        console.log("prev: ", this.previousUrl)                        console.log("curr: ", this.currentUrl)                    });    }    public getPreviousUrl() {        return this.previousUrl;    }};