Angular

Get the Current Route in Angular 15 Example

Pinterest LinkedIn Tumblr

In Angular 15, you can use the ActivatedRoute class to get the current route. Here’s an example of how you can use it:

  1. First, import the ActivatedRoute class and the Router class in your component:
Copy codeimport { ActivatedRoute, Router } from '@angular/router';
  1. In your component’s constructor, inject the ActivatedRoute and Router services:
Copy codeconstructor(private route: ActivatedRoute, private router: Router) { }
  1. To get the current route, you can use the route.url property. This property returns an observable that emits an array of the URL segments.
Copy codengOnInit() {
    this.route.url.subscribe(url => {
        console.log(url);
    });
}
  1. You can also use route.snapshot.url to get the current route’s URL segments as an array of strings.
Copy codengOnInit() {
    console.log(this.route.snapshot.url);
}
  1. To get the current route parameters you can use the route.params property. This property returns an observable that emits an object containing the route parameters.
Copy codengOnInit() {
    this.route.params.subscribe(params => {
        console.log(params);
    });
}
  1. You can also use route.snapshot.params to get the current route parameters as an object.
Copy codengOnInit() {
    console.log(this.route.snapshot.params);
}

Note that the router service is not necessary to get the route, you can use the ActivatedRoute service for that. However, the Router service is useful for other operations such as navigate to different pages.

Write A Comment