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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With