I was trying to use ActivatedRoute in a service and was noticing that it didn't seem to be tracking the route that I was currently on. In fact it wouldn't seem to pick up any route. It took me far too long to figure out what was going on and I wasn't able to find many helpful answers online(probably because most people are a lot quicker than me :) ).
Just wanted to make sure that I posted something so that some others can find the solution faster.
Here's what my code looked like when I was having the issue.
@Injectable()
export class ImdbService {
constructor(private router: Router,
private route: ActivatedRoute) {
}
closeDetails(): void {
this.detailsOpened = false;
this.router.navigate(['../'], {relativeTo: this.route});
}
Difference between activatedroute and routerstateRouterState is an interface which represents the state of the router as a tree of activated routes. Every node of this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data.
ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet. Use to traverse the RouterState tree and extract information from nodes.
ActivatedRoute Contains the information about a route associated with a component loaded in an outlet. It can also be used to pass data from one component to another component using route such as Id, flag, state etc.
Because the services seem to not have the same interaction with ActivatedRoute when injected as the components do my solution was to pass the ActivatedRoute as a param in the service call I was using.
Here's what the solution that worked for me looks like:
@Injectable()
export class ImdbService {
constructor(private router: Router) {
}
closeDetails(currentRoute): void {
this.detailsOpened = false;
this.router.navigate(['../'], {relativeTo: currentRoute});
}
And in the component:
export class MovieDetailsComponent implements OnInit, OnDestroy {
constructor(..., private route: ActivatedRoute ) { }
closeDetails() {
this.imdbService.closeDetails(this.route);
}
If anyone has a better or even just a different solution to this issue or if there's a good reason to do this in an entirely different way I'd love to see it.
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