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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With