Get previous route Angular 7
If you just want the previous route you can create an observable like this
public previousRoute$: Observable<string> = 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.
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