David Baxter
David Baxter

Reputation: 235

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

Upvotes: 10

Views: 4945

Answers (2)

Flavien Volken
Flavien Volken

Reputation: 21299

Inject your service directly within the component

@Component({
  ...
  providers: [ImdbService], // provide your service here so it will be instanciated with your component.
})

export class MovieDetailsComponent implements OnInit, OnDestroy {

  constructor(..., private imdbService: ImdbService ) { }

  closeDetails() {
    this.imdbService.closeDetails();
  }

Upvotes: 4

David Baxter
David Baxter

Reputation: 235

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.

Upvotes: 9

Related Questions