Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

url property of NavigationEnd returns undefined (Angular 6)

I'm relatively new to front-end stuff, I was playing around with Angular 6, so the issue I'm facing with the following component is that NavigationEnd returns undefined and I can't figure out why:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit {
  currentUrl: string;

  constructor(private router: Router) {
    router.events.subscribe(
      (navEnd: NavigationEnd) => this.currentUrl = navEnd.url
    );
  }
}
like image 342
TheBinaryGuy Avatar asked Jul 28 '18 18:07

TheBinaryGuy


3 Answers

router.events has different events, if you need to get the NavigationEnd you need to filter as follows. Try this,

 router.events
      .pipe(filter(e => e instanceof NavigationEnd))
      .subscribe((e: NavigationEnd) => {
        this.currentUrl = e.url;       
 });
like image 105
Sajeetharan Avatar answered Oct 16 '22 15:10

Sajeetharan


You need to check which type of events you receive from the subscribe method.

Also you need to use this to access router ( it's a private variable)

 constructor(private router: Router) {
this.router.events
  .subscribe((event) => {
    if (event instanceof NavigationEnd) {
      this.currentUrl = event.url
      console.log('NavigationEnd:', event);
    }
  })
like image 2
Melchia Avatar answered Oct 16 '22 13:10

Melchia


I think what you are trying to achive is the following.

this.router.events.pipe(
    filter((event) => event instanceof NavigationEnd),
    map(() => this.activatedRoute)
 ).subscribe((event) => {
       this.currentUrl = event.url
});

Inject ActivatedRoute in the constructor.

like image 2
René Winkler Avatar answered Oct 16 '22 14:10

René Winkler