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
);
}
}
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;
});
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);
}
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With