Angular 2.0.2: ActivatedRoute is empty in a Service

The answer of estus provides a good solution when multiple service instances are not an issue.

The following solution gets a parameter straight from the router and allows the service to have one instance:

export class Service {
  result: string;

  constructor(private router: Router) {
    this.result = router.routerState.snapshot.root.children[0].url[index].path
  }
}

or as an observable:

export class Service {
  result: string;

  constructor(private router: Router) {
    this.router.routerState.root.children[0].url.map((url) => {
      this.result = url[index].path;
    });
  }
}

alternatively, when routerState is not available:

export class Service {
  result: string;

  constructor(private router: Router) {
    this.router.parseUrl(this.router.url).root.children.primary.segments[index].toString();
  }
}

Index is the position of the param in the url.


Service here is a singleton that belongs to root injector and is injected with root ActivatedRoute instance.

Outlets get their own injector and own ActivatedRoute instance.

The solution here is to let route components have their own Service instances:

@Component({
  ...
  providers: [Service]
})
export class MainComponent { ... }

I came across this issue and the working solution I end with is the following.

@Component({
  selector: 'app-sample',
  styleUrls: [`../sample.component.scss`],
  templateUrl: './sample.component.html',
})
export class AppSampleComponent {
  constructor(private route: ActivatedRoute,
              private someService: SomeService){}
  public callServiceAndProcessRoute(): void {
    this.someService.processRoute(route);
  }
}

@Injectable()
export class SomeService {
  public processRoute(route: ActivatedRoute): void {
  // do stuff with route
  }
}

So you will pass the ActivatedRoute to the service as a param.