Get previous route Angular 7

Testador picture Testador · Dec 11, 2018 · Viewed 32.8k times · Source

I created a little service where I can store the route changes.

import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable()
export class RouteState {

  private previousUrl: string;
  private currentUrl: string;

  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;
  }    
}

But everytime the route change the vars currentUrl and previousUrl are undefined. Am I doing something wrong?

Answer

siddharth shah picture siddharth shah · Dec 11, 2018

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