Joseph Chikeme
Joseph Chikeme

Reputation: 512

Angular Router.url not updating current path

My header component Router.url always returns a slash '/' rather than the navigated URL.

    currentLink?: string = ''

  constructor(private route: Router) { }

  ngOnInit(): void {
    this.getUrl()
  }

The app component where it's been used.

<app-header></app-header>

<router-outlet></router-outlet>
    
      getUrl() {
        this.currentLink = this.route.url
      }

I have tried AfterContentInit on child component still didn't work

Upvotes: 2

Views: 3289

Answers (2)

Peter O Brien
Peter O Brien

Reputation: 191

The router.url is only populated at NavigationEnd event.
An alternative solution to subscribe of router.events > NavigationEnd , is to use location.path()

The location.path() is populated with current view path and url params and is available at any stage of the life cycle - so useful for ad hoc query of url.

import:

import { Location } from '@angular/common';
import { PRIMARY_OUTLET, UrlSegment, UrlSegmentGroup, UrlTree, Router, Params } from '@angular/router';

constructor(private location: Location, private router: Router, ...

Common usage - to extract URL segments and params.

const routeTree: UrlTree = router.parseUrl(this.location.path());

const routeSegmentGroup: UrlSegmentGroup = routeTree.root.children[PRIMARY_OUTLET];

var segmentList: UrlSegment[] = [];

if (routeSegmentGroup != undefined) {
   segmentList = routeSegmentGroup.segments;
}

Upvotes: 1

Slawa Eremin
Slawa Eremin

Reputation: 5415

It's possible to get params from url through ActivatedRoute service only if component is placed inside <router-outlet>, in other cases(and I think, it's your case) you should use NavigationEnd event:


export class Component {

  ngOnInit() {
    this.router.events
      .pipe(
        delay(10),
        filter((e) => e instanceof NavigationEnd),
      )
      .subscribe((event: RouterEvent) => {
        console.log(event.url);
      });
  }
}


Upvotes: 4

Related Questions