Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 router event not firing first time?

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?

like image 992
David Aguirre Avatar asked Apr 05 '17 16:04

David Aguirre


2 Answers

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  }) 
like image 115
Kurkov Igor Avatar answered Oct 04 '22 08:10

Kurkov Igor


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:

  1. Let the Component subscribe to the NavigationEnd event as before.
  2. Make the 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.

like image 44
TekTimmy Avatar answered Oct 04 '22 08:10

TekTimmy