Angular 9 router events on lazy loaded module

Viewed 1300

I am struggling with the Router.events observable given by Angular. My application has two lazy loaded module. Each have a navmenu that display some links to navigate inside the application. I want one of my link to appear as selected depending on the current route.

The thing is that when I use the async pipe of an observable based on the router.events obserable, the routing events have already been emitted before my template is handled by angular.

I Kknow that if I subscribe manually inside the constructor of my component, I can get the data. If I do the same inside the ngOnInit function, same as with the async pipe, there are no data emitted. It's working fine if I navigate using a link after the page is loaded.

Do you know a way on how I could achieve that ?

Thanks !

1 Answers

I someone needs it, this is how I fix it. If you have lazy loaded modules, make sure to import this service on the root component so the subscribe happens at the very beginning.

import {Injectable} from '@angular/core';
import {Observable, ReplaySubject} from 'rxjs';
import {filter, map, tap} from 'rxjs/operators';
import {NavigationEnd, Router} from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class RouterService {

  _events = new ReplaySubject<string>();

  constructor(private readonly router: Router) {
    router.events.pipe(
      filter(e => e instanceof NavigationEnd),
      map(e => e as NavigationEnd),
      map((e: NavigationEnd) => e.urlAfterRedirects),
      tap((url) => this._events.next(url))
    ).subscribe();
  }

  get events(): Observable<string> {
    return this._events.asObservable();
  }
}
Related