Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Service variables being reset on route change

I have a service that i am using to keep track of the state of my model. I have multiple components that i would like to have access this service variables properties. When the first component loads on init, i set the model, yet when i try to access this model from my second component after route change, the variable is now undefined. Below is an example of what im talking about.

Component 1

constructor(private service: Service, private route)

ngOninit(){
  this.service.setModel();
  console.log(this.service.getModel()); <-- works fine
}

componentButton1Click(){
  route.navigateByUrl(component2route) <--works fine
}

Component 2

constructor(private service: Service)

ngOninit(){
  console.log(this.service.index); <-- undefined
}

Service

private index: number;

constructor(private http: Http)

getModel(){
   return this.index; <-- works fine
}

setModel(){
  this.index = this.http.get('somejsonfile.json').index;
}
like image 568
Monzingo Avatar asked Aug 22 '17 18:08

Monzingo


1 Answers

The most common cause of this issue is that the service is registered more than one time. Check the contents of the providers array in each of your components and modules and ensure that it is only registered in ONE place.

Here is a code snippet:

  providers: [
    ProductService,
    ProductGuardService
  ]

These are part of the @Component or @NgModule metadata

like image 129
DeborahK Avatar answered Oct 23 '22 16:10

DeborahK