-1

I'm trying to fetch the current route of my application and in this article on Angular's doc site they have this code

@Component({
  selector: 'app-routable',
  template: 'Routable2Component template'
})
export class Routable2Component implements OnInit {
  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.activatedRoute.url
      .subscribe(url => console.log('The URL changed to: ' + url));
  }
}

So in my own code I do this

CurrentPage!: string;

constructor(
    private currentRoute: ActivatedRoute
){}

ngOnInit(): void {
    this.currentRoute.url.subscribe(a => {
      this.CurrentPage = a;
    });
}

However things didn't behave the way I thought they would so I commented out the assignment and did console.log(a) and saw the url is an array. Inside this array there's an object with a path property which is empty. Am I missing something here? How do I get this to work as the doc pages suggest?

Optiq
  • 2,835
  • 4
  • 33
  • 68

2 Answers2

0

You can try like below to get the current route from activated route. Angular docs have the info if route changes from another component to current component, then it will emit the current route details in subscribe.

 ngOnInit() {
    let currentPath = activatedRoute.url.value[0].path;
    console.log(currentPath);
 }

You can also refer this link for more details on getting current route - How to get current route

Ganesh
  • 5,808
  • 2
  • 21
  • 41
0

The url property of ActivatedRoute is an observable of an array of UrlSegment objects, rather than a simple string. Here is how it's done:

ngOnInit(): void {
  this.currentRoute.url.subscribe(segments => {
    this.CurrentPage = segments.map(segment => segment.path).join('/');
    console.log('Current Page:', this.CurrentPage);
  });
}
MaikeruDev
  • 1,075
  • 1
  • 19