Angular2 Service variables being reset on route change

时光毁灭记忆、已成空白 提交于 2020-01-24 10:06:06

问题


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;
}

回答1:


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



来源:https://stackoverflow.com/questions/45824330/angular2-service-variables-being-reset-on-route-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!