[英]How to use same instance of an injected service across different components in Angular?
I'm currently trying to access the real-time value of a variable in a service from different components.我目前正在尝试从不同组件访问服务中变量的实时值。
In my service I have:在我的服务中,我有:
export class ServiceA {
serviceVar = "hello";
constructor(private httpClient: HttpClient) {
}
getServiceVar(){
return this.serviceVar
}
setServiceVar(newVar){
this.serviceVar = newVar;
}
in Component AI have:在组件 AI 中有:
export class ComponentA implements OnInit {
constructor(private service: ServiceA) {}
setVar() {
this.service.setServiceVar("new value from A")
}
getVar(){
console.log(this.service.getServiceVar())
}
}
in Component BI have:在组件 BI 中有:
export class ComponentB implements OnInit {
constructor(private service: ServiceA) {}
setVar() {
this.service.setServiceVar("new value from B")
}
getVar(){
console.log(this.service.getServiceVar())
}
}
in app.module.ts在 app.module.ts
providers: [ServiceA]
If I set the variable in ComponentA, I would like ServiceA's variable to be updated in a way so that if ComponentB tries to get() that value, it receives the value that ComponentA updated the service with.如果我在 ComponentA 中设置变量,我希望以某种方式更新 ServiceA 的变量,以便如果 ComponentB 尝试 get() 该值,它会收到 ComponentA 更新服务所用的值。 Essentially having ComponentA and ComponentB using the same instance of the service.
本质上让 ComponentA 和 ComponentB 使用相同的服务实例。
Right now what is happening is that there are 2 instances of ServiceA, and when ComponentA runs setVar(), the change is only applied to ComponentA's instance of the service and not to the ComponentB's instance of the service.现在发生的事情是有 2 个 ServiceA 实例,当 ComponentA 运行 setVar() 时,更改仅应用于 ComponentA 的服务实例,而不应用于 ComponentB 的服务实例。
I can see your code is completely correct as you have registered the service app.module.ts.我可以看到你的代码是完全正确的,因为你已经注册了服务 app.module.ts。 So, there will be a singleton instance of service.
所以,会有一个服务的单例实例。
The only thing that you need to correct is service class where you need to add property called spreadsheetID.您唯一需要更正的是服务类,您需要在其中添加名为电子表格 ID 的属性。 strong text
强文本
export class ServiceA {
serviceVar = "hello";
spreadsheetID
constructor(private httpClient: HttpClient) {
}
getServiceVar(){
return this.spreadsheetID
}
setServiceVar(newSpread){
this.spreadsheetID = newSpread;
}
The answer is to make your Service a provider just as I did in my question...BUT also make sure you remove答案是让你的服务成为一个提供者,就像我在我的问题中所做的那样......但也要确保你删除
@Injectable({
providedIn: 'root'
})
and change it to just:并将其更改为:
@Injectable()
at the top of your service :)在您的服务之上:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.