Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.router.events not loading on first time in Angular

Does anyone have any idea on how to get the router events to fire the first time the component is loaded?

I am using Angular 8.

I have a deep link that moves to another component. So when I click on the deep link its redirect to the Home page. This happens whenever the computer starts a new session.

So as per my investigation when the app loads for the first time it (this.router.events) returns nothing.

Can anyone please suggest to me regarding it.

Following is my code:- app.component.ts

 ngAfterViewInit() {
    this.getActivatedRoute();
}
getActivatedRoute() {
    debugger
    const routerSub$ = this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.routes = event.url.toLowerCase().split('/');
        this.currentRoute = this.routes[1];
        if (this.currentRoute !== this.previousRoute) {
          this.setBodyClassBasedOnRouter(this.routes);
          this.previousRoute = this.currentRoute;
        }
      }
    });
  }
like image 227
Aakankshi Gupta Avatar asked Dec 12 '25 02:12

Aakankshi Gupta


1 Answers

The NavigationEnd event has already been raised when the component registers for it. best solution would be to use the rxjs startWith operator, and let the component load the initial state from the injected Route, like this:

const routerSub$ = this.router.events.pipe(
  filter((e) => e instanceof NavigationEnd),
  startWith(this.router)).
  subscribe((event) => {
        this.routes = event.url.toLowerCase().split('/');
        this.currentRoute = this.routes[1];
        if (this.currentRoute !== this.previousRoute) {
          this.setBodyClassBasedOnRouter(this.routes);
          this.previousRoute = this.currentRoute;
        }
    });

Pay attention to the fact that HTML elements are still not rendered when the constructor is running (if used inside the constructor).

like image 135
Elazar Zadiki Avatar answered Dec 14 '25 16:12

Elazar Zadiki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!