Home > Software engineering >  Get router state from URL in Angular
Get router state from URL in Angular

Time:02-25

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?

UPDATE

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.

CodePudding user response:

May be you try this:

@Component({templateUrl:'template.html'})
class MyComponent {
  constructor(router: Router) {
    const state: RouterState = router.routerState;
    const root: ActivatedRoute = state.root;
    const child = root.firstChild;
    const id: Observable<string> = child.params.map(p => p.id);
    //...
  }
}

CodePudding user response:

See updated text for a solution.

  • Related