this.router.events not loading on first time in Angular
Asked Answered
A

4

16

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;
        }
      }
    });
  }
Ammonal answered 11/6, 2020 at 13:55 Comment(3)
Can you please share more code?Dermatitis
#43237818 Hope this would help youRajiv
@LasalSethiya Okay Let me checkAmmonal
R
26

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).

Runoff answered 3/4, 2022 at 11:37 Comment(1)
neat, first time to use startWithAweinspiring
K
4

use it in the constructor

import { NavigationEnd, Router } from '@angular/router'; 
class ...   
constructor(private router:Router) {
    
        this.router.events
        .pipe(
          filter(event => event instanceof NavigationEnd),
          map((event: NavigationEnd) => event.url))
        .subscribe(url => {
    
          const lastUrlSegment = url.split('?')[0].split('/').pop()
          console.log(lastUrlSegment)
          console.log(url)
        });
    
    }
Kathe answered 30/11, 2021 at 19:6 Comment(0)
B
0

First load working with ActivatedRoute

...
constructor(public activatedroute: ActivatedRoute,) {}
... 
this.activatedroute.url.subscribe(data=>{
            ....
     })
Bradbury answered 2/9, 2021 at 4:54 Comment(0)
R
0

You don't need router.event. you can just use router.url for first loading.

otherwise you can use ActivatedRoute state snapshot url for first time and router event for next routings:

constructor(
  private route: ActivatedRoute,
  private router: Router,
){
  let activeRoute = this.route['_routerState']['snapshot'].url;
      
  this.routes = activeRoute.toLowerCase().split('/');
  this.currentRoute = this.routes[1];
  if (this.currentRoute !== this.previousRoute) {
    this.setBodyClassBasedOnRouter(this.routes);
    this.previousRoute = this.currentRoute;
  }

  this.router.events.subscribe({
    next: (rEvent: any) => {
      if(rEvent instanceof NavigationEnd) {
        this.routes = this.router.url.toLowerCase().split('/');
        this.currentRoute = this.routes[1];
        if (this.currentRoute !== this.previousRoute) {
          this.setBodyClassBasedOnRouter(this.routes);
          this.previousRoute = this.currentRoute;
        }
      }
    }
  )}      
}
Rhetic answered 1/10, 2023 at 19:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.