Angular2服务变量在路线更改时被重置 [英] Angular2 Service variables being reset on route change
问题描述
我有一项用于跟踪模型状态的服务.我有多个组件,希望访问此服务变量属性.当第一个组件加载到init时,我设置了模型,但是当我尝试在更改路线后从第二个组件访问该模型时,该变量现在未定义.以下是即时通讯正在谈论的示例.
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.
组件1
constructor(private service: Service, private route)
ngOninit(){
this.service.setModel();
console.log(this.service.getModel()); <-- works fine
}
componentButton1Click(){
route.navigateByUrl(component2route) <--works fine
}
组件2
constructor(private service: Service)
ngOninit(){
console.log(this.service.index); <-- undefined
}
服务
private index: number;
constructor(private http: Http)
getModel(){
return this.index; <-- works fine
}
setModel(){
this.index = this.http.get('somejsonfile.json').index;
}
推荐答案
此问题的最常见原因是该服务已多次注册.检查每个组件和模块中providers
数组的内容,并确保它仅在 ONE 位置注册.
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.
这是一个代码段:
providers: [
ProductService,
ProductGuardService
]
这些是@Component
或@NgModule
元数据的一部分
These are part of the @Component
or @NgModule
metadata
这篇关于Angular2服务变量在路线更改时被重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!