Consider the following service,
@Injectable()
export class SagasService {
constructor(private route : ActivatedRoute, private router : Router ){
router.events
.filter(e => e instanceof NavigationStart)
.subscribe(e=>{
route.url.subscribe(a=>console.log(a[0].path));
});
}
}
Every time the route changes, the console.log()
triggers. But, no matter what the route, the value is always ""
(empty string).
What is wrong here?
Steps to get current route URL in Angular. Import Router,NavigationEnd from '@angular/router' and inject in the constructor. Subscribe to the NavigationEnd event of the router. Get the current route url by accessing NavigationEnd's url property.
Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute . It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.
The ActivatedRoute is the API that holds observable data that you can use to react to events with. You can subscribe to specific observable properties to get data from it asynchronously. The ActivatedRoute also contains ActivatedRouteSnapshot.
The definition of the ActivatedRoute is:
Contains the information about a route associated with a component loaded in an outlet. An ActivatedRoute can also be used to traverse the router state tree.
That means that if you inject it in the service, you will get the ActivatedRoute
from the AppComponent. Which would always have the path of ""
.
You can traverse the state tree to find the last activated route like
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map(route => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
map(route => route.url)
)
.subscribe( // ... do something with the url)
if you want to get the current URL, you can import the location import from angular/common as below
import {Location} from '@angular/common';
constructor(public location: Location ){ }
let currentUrl = this.location.path();
can be used in NavigationEnd subscriber
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