Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActivatedRoute isn't working in Service

ActivatedRoute in Services

The Problem

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});
  }
like image 338
David Baxter Avatar asked Dec 08 '17 16:12

David Baxter


People also ask

What is difference between router and ActivatedRoute?

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.

What does the ActivatedRoute interface allows you to access?

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.

Why activated route is used?

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.


1 Answers

My Solution

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);
  }

Got something better?

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.

like image 168
David Baxter Avatar answered Oct 04 '22 02:10

David Baxter