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?
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)