如何更改服务中变量的值并将其反映在使用该服务的组件中
How to change value of a variable in service and reflect it in a component that uses that service
我需要一点帮助。我有一个组件和一个服务。该组件依赖于一个变量,该变量的值取决于服务中的另一个变量。变量(正在使用的变量)最初是 false
,但在收到响应后应该变为 true
(此时我正在使用一些 Observable-Subscribe 代码来模拟 HTTP GET 调用)。现在相同的 true
值没有反映在我的组件中。那就是问题所在。这是代码:
app.component.html
<h2>Current status: {{ status }}</h2>
<button (click)="onButtonPress()" >Click</button>
app.component.ts
export class AppComponent {
status: boolean;
constructor(private _myService: MyserviceService) {}
ngOnInit() {
this.status = this._myService.serviceStatus;
}
onButtonPress() {
this._myService.takeAction();
}
}
myservice.service.ts
export class MyserviceService {
serviceStatus: boolean = false;
constructor() {
}
takeAction() {
interval(1000)
.pipe(take(5), toArray())
.subscribe((res) => {
console.log(res);
this.serviceStatus = true;
});
}
}
我创建了一个 stackblitz。请看看并随时指出代码中的错误。谢谢。
请尝试在服务中创建 BehaviorSubject 变量,例如
serviceStatus = new BehaviourSubject(false); // 默认值为假
并在 takeAction 方法中将 serviceStatus 变量的值更改为 true,例如
this.serviceStatus.next(真);
在 ngOnInit 的 app.component.ts 中订阅 serviceStatus 变量,例如
this._myService.serviceStatus.pipe(takeUntil(this.destroy$)).subscribe(data => this.status = data); // takeUntil 用于在组件被销毁时取消订阅 - 防止内存泄漏
我需要一点帮助。我有一个组件和一个服务。该组件依赖于一个变量,该变量的值取决于服务中的另一个变量。变量(正在使用的变量)最初是 false
,但在收到响应后应该变为 true
(此时我正在使用一些 Observable-Subscribe 代码来模拟 HTTP GET 调用)。现在相同的 true
值没有反映在我的组件中。那就是问题所在。这是代码:
app.component.html
<h2>Current status: {{ status }}</h2>
<button (click)="onButtonPress()" >Click</button>
app.component.ts
export class AppComponent {
status: boolean;
constructor(private _myService: MyserviceService) {}
ngOnInit() {
this.status = this._myService.serviceStatus;
}
onButtonPress() {
this._myService.takeAction();
}
}
myservice.service.ts
export class MyserviceService {
serviceStatus: boolean = false;
constructor() {
}
takeAction() {
interval(1000)
.pipe(take(5), toArray())
.subscribe((res) => {
console.log(res);
this.serviceStatus = true;
});
}
}
我创建了一个 stackblitz。请看看并随时指出代码中的错误。谢谢。
请尝试在服务中创建 BehaviorSubject 变量,例如 serviceStatus = new BehaviourSubject(false); // 默认值为假 并在 takeAction 方法中将 serviceStatus 变量的值更改为 true,例如 this.serviceStatus.next(真);
在 ngOnInit 的 app.component.ts 中订阅 serviceStatus 变量,例如 this._myService.serviceStatus.pipe(takeUntil(this.destroy$)).subscribe(data => this.status = data); // takeUntil 用于在组件被销毁时取消订阅 - 防止内存泄漏