Home > OS >  Angular Router.url not updating current path
Angular Router.url not updating current path

Time:03-09

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

CodePudding user response:

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);
      });
  }
}


  • Related