Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

496
Vistas
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?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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
 })
about 4 years ago · Santiago Trujillo Denunciar

0

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.

about 4 years ago · Santiago Trujillo Denunciar

0

I had exactly the same scenario and I found out that it's too late to subscribe for NavigationEnd with pairwise in the constructor of the child component.

You could subscribe to the router in your root component and share the route data through a service like the following example:

events.service.ts

import { Injectable } from '@angular/core';
import { RouteChanged } from '../models/route-changed.model';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class EventsService {
  public routeChanged = new BehaviorSubject<RouteChanged>({ prevRoute: '/', currentRoute: '/' });

  constructor() {
  }
}

app.component.ts (your root component)

...

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
    private subscriptions = new Subscription();

    constructor(private eventsService: EventsService) {
            this.subscriptions.add(this.router.events
                .filter(event => event instanceof NavigationEnd)
                .pairwise()
                .subscribe(navigationEvents => {
                    const prevPage = <NavigationEnd>navigationEvents[0];
                    const currentPage = <NavigationEnd>navigationEvents[1];
                    this.eventsService.routeChanged.next(
                        { prevRoute: prevPage.urlAfterRedirects, currentRoute: currentPage.urlAfterRedirects });
                }));
        }

    ngOnDestroy(): void {
        this.subscriptions.unsubscribe();
    }

    ...
}

your-target-route.ts

...
constructor(private eventsService: EventsService) {
    this.subscriptions.add(this.eventsService.routeChanged.subscribe((routeChanged) => {
        // use routeChanged.prevRoute and routeChanged.currentRoute here...
    }));
}

P.S. It's important to use a BehaviorSubject or a ReplaySubject in the service in order to get the proper previous route event if your child component subscribes after the page load.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda