Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2.0.2: ActivatedRoute is empty in a Service

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'];     });   } } 
like image 226
Steve Van Opstal Avatar asked Oct 11 '16 13:10

Steve Van Opstal


People also ask

Is ActivatedRoute a service?

Service is a singleton. ActivatedRoute is not. I guess that ActivatedRoute instances are just different in Component and Service. @estus Makes sense, I could pass the param to the service via a function.

How do I use ActivatedRoute?

Step 1: Import ActivatedRoute from Router module. import { ActivatedRoute } from '@angular/router'; Step 2: Inject ActivatedRoute in constructor. Now we have id in edit_quiz.

Why do we use ActivatedRoute in angular?

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.


1 Answers

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 { ... } 
like image 154
Estus Flask Avatar answered Oct 05 '22 11:10

Estus Flask