Maybe all other answers are for angular 2.X.
Now it doesn't work for angular 5.X.
I'm working with it.
with only NavigationEnd, you can not get previous url.
because Router works from "NavigationStart", "RoutesRecognized",..., to "NavigationEnd".
You can check with
router.events.forEach((event) => {
console.log(event);
});
But still you can not get previous url even with "NavigationStart".
Now you need to use pairwise.
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/pairwise';
constructor(private router: Router) {
this.router.events
.filter(e => e instanceof RoutesRecognized)
.pairwise()
.subscribe((event: any[]) => {
console.log(event[0].urlAfterRedirects);
});
}
With pairwise, You can see what url is from and to.
"RoutesRecognized" is the changing step from origin to target url.
so filter it and get previous url from it.
Last but not least,
put this code in parent component or higher (ex, app.component.ts)
because this code fires after finish routing.
Update angular 6+
The events.filter
gives error because filter is not part of events, so change the code to
import { filter, pairwise } from 'rxjs/operators';
this.router.events
.pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
.subscribe((events: RoutesRecognized[]) => {
console.log('previous url', events[0].urlAfterRedirects);
console.log('current url', events[1].urlAfterRedirects);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…