I am routing from one component to another. Once the route is done I would like to use the URL from the previous route. I have put the code below into the constuctor of the component being routed to, but it does not fire on the first route. After the first route, the function fires every time.
this.router.events .filter(e => e instanceof NavigationEnd) .pairwise().subscribe((e) => { console.log(e); });
If I remove the pairwise function it seems to fire on first route, however it lists only the current route, not the previous route.
router.events .filter(e => e instanceof NavigationEnd) .subscribe(e => { console.log(e); });
My goal is to retrieve the previous route when the new component is routed to. What am I doing wrong here?
As I see all these solutions relay to route.snapshot
and try to combine NavigationEnd action with it. But if you try to access the page - it is not fired with the first NavigationEnd
by router.events
. Also snapshot fires parent route, not a child route. so first you could use child route, but it will be also not fired as first...
this.router.events.pipe( filter((event) => event instanceof NavigationEnd), map(() => this.aRoute.snapshot), map((route) => { while (route.firstChild) { route = route.firstChild; } return route; }) )
so BEST solution for me with first fire on proper current route is using router.events
+ router.url
with one type NavigationEnd
:
this.router.events .pipe( filter((event) => event instanceof NavigationEnd), startWith(this.router) ) .subscribe((event: NavigationEnd) => { // there will be first router.url - and next - router events })
The answer was already given: The NavigationEnd
event has already been raised when the component registers for it. I don't like the idea of "Dimitar Tachev" to create a workaround by proxying those events through a subject. In my case the solution was to:
Component
subscribe to the NavigationEnd
event as before.Component
load the initial state from the injected Route
object in the ngOnInit
method.And finally another solution is to move the subscription to the route change events into the constructor of the component.
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