In Angular 15, you can use the ActivatedRoute
class to get the current route. Here’s an example of how you can use it:
- First, import the
ActivatedRoute
class and theRouter
class in your component:
Copy codeimport { ActivatedRoute, Router } from '@angular/router';
- In your component’s constructor, inject the
ActivatedRoute
andRouter
services:
Copy codeconstructor(private route: ActivatedRoute, private router: Router) { }
- 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);
});
}
- 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);
}
- 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);
});
}
- 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.