I want to use ActivatedRoute to get route params in a service like I would do in a Component. However, when I inject the ActivatedRoute object in a Service it contains an empty params variable
I've created a plunker that reproduces the behaviour: http://plnkr.co/edit/sckmDYnpIlZUbqqB3gli
Note that the intention is to use the parameter in the service and not in the component, the way the plunker is set up is purely to demonstrate the issue.
Component (test
is retrieved):
export class Component implements OnInit {
result: string;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.params.subscribe(params => {
this.result = params['test'];
});
}
}
Service (test
is not retrieved):
export class Service {
result: string;
constructor(private route: ActivatedRoute) {
this.getData();
}
getData() {
this.route.params.subscribe(params => {
this.result = params['test'];
});
}
}
Service
is a singleton.ActivatedRoute
is not. I guess thatActivatedRoute
instances are just different in Component and Service. – PellitoryReplaySubject
to store/observe the required values. Felt like a simple solution at least for me: https://mcmap.net/q/371796/-how-can-a-service-subscribe-to-the-parammap-of-the-current-route – Landing