Search code examples
angularangular-router

Get router state from URL in Angular


Using the router events I can see the navigation changes and the updated URL. But how do I get the actual router state (data, resolves, parameters, etc) from the URL. I tried using the ActivatedRoute but this is only initialized once the component is initialized.

Current code:

@Component({...})
export class SecundaryMenuComponent implements OnInit, OnDestroy {
  private titleSubject$: BehaviorSubject<string> = new BehaviorSubject<string>('');
  public title$: Observable<string> = this.titleSubject$.asObservable();

  private navSubscription: Subscription;

  constructor(private router: Router, private activeRoute: ActivatedRoute) {
    this.navSubscription = this.router.events.subscribe((event: NavigationEvent) => {
      this.handleRoutingEvent(event);
    });
  }

  ngOnInit(): void {}

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

  handleRoutingEvent(event: NavigationEvent) {
    if (event instanceof NavigationEnd) {
      this.titleSubject$.next(event.urlAfterRedirects);
    }
  }
}

So how can I access the active router state in the handleRoutingEvent function?


Solution

  • After more searching I found this and changed my code to the following:

    @Component({...})
    export class SecundaryMenuComponent implements OnInit, OnDestroy {
      private titleSubject$: BehaviorSubject<string> = new BehaviorSubject<string>('');
      public title$: Observable<string> = this.titleSubject$.asObservable();
    
      private routeUrl$: Observable<UrlSegment[]>;
      private routeUrlSubscription: Subscription;
    
      constructor(private router: Router, private route: ActivatedRoute) {
        this.routeUrl$ = this.router.events.pipe(
          filter((event) => event instanceof NavigationEnd),
          switchMap(() => {
            const url = this.route.firstChild?.url;
            return url || of();
          })
        );
    
        this.routeUrlSubscription = this.routeUrl$.subscribe((url) => this.handleRouteUrl(url));
      }
    
      ngOnInit(): void {}
    
      ngOnDestroy(): void {
        this.routeUrlSubscription.unsubscribe();
      }
    
      handleRouteUrl(url: UrlSegment[]) {
        let routeUrl = '/' + url.join('/');
        this.titleSubject$.next(routeUrl);
      }
    }
    

    Now I get the proper title based on the actual router data instead of the event URL. The same principle can also be used to get the parameters, data, etc.