[英]Angular Service variable not updating in Component
I have a boolean variable in a service that is updated in function.我在功能更新的服务中有一个布尔变量。 I want to use this variable change in the component, but the service variable is not updating in the component.我想在组件中使用此变量更改,但服务变量未在组件中更新。
service.ts服务.ts
isUpdating: boolean;
updateTheVairable() {
this.isUpdating = true;
}
component.ts组件.ts
methodRequiringUpdateFromService() {
if(this.service.isUpdating) {
//do something
}
}
The isUpdating variable in service variable is assigned to true, but it is not updating in the component. service变量中的isUpdating变量被赋值为 true,但在组件中并没有更新。 Any help would be greatly appreciated :)任何帮助将不胜感激:)
You might use Subject
or if you need an initial value then BehaviorSubject
from rxjs
in your service then subscribe to it in you component.您可以使用Subject
或者如果您需要一个初始值,则在您的服务中使用来自rxjs
BehaviorSubject
然后在您的组件中订阅它。
Service:服务:
isUpdatingSubject: BehaviorSubject<boolean> = new BehaviorSubject(false); // inital value is "false"
isUpdating = this.isUpdatingSubject.asObservable();
setUpdateState = (newState) => {
this.isUpdatingSubject.next(newState);
}
Component:成分:
ngOnInit(){ // You may use another method, such as "constructor" or custom one
this.service.isUpdating.subscribe((isUpdating) => {
if(isUpdating){
//do something
}
})
}
Note: Don't forget to unsubscribe from the service on ngDestroy.注意:不要忘记取消订阅 ngDestroy 上的服务。
You have not invoked the method - updateTheVairable() in the service.ts to set the value.您尚未调用 service.ts 中的方法 - updateTheVairable() 来设置值。
methodRequiringUpdateFromService(){
this.service.updateTheVairable()
if(this.service.isUpdating){
//do something
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.