Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

495
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!