如何监听 Angular 中组件中的服务变量变化
How can I listen for a Service variable change in a component in Angular
我有一个带有按钮的组件,单击该按钮会触发 showSummary()
,该组件会调用具有方法 calc()
的服务 Appraisal-summary.service.ts
showSummary(appraisal) {
this.summaryService.calc(appraisal);
}
有服务 Appraisal-summary.service.ts
:
calc(appraisal) {
...
//a 'scores' array is created (synchronously)
return this.scores;
}
如何侦听同步结果 this.scores
以触发将使用 scores
.[=22 的不相关组件 summary.component.ts
(已初始化)中的函数=]
类似于:
summary.component.ts
:
ngOnInit(): void {
service.subscribe(scores => this.data = scores)
}
你会想在你的 Appraisal-summary.service.ts
中添加一个 Subject
像这样:
import { Subject } from 'rxjs';
...
export class AppraisalSummaryService {
// I am guessing scores is an array of type number
public scoreSubject = new Subject<number[]>();
calc(appraisal) {
...
//a 'scores' array is created (synchronously)
this.scoreSubject.next(this.scores); //emit the scores result
return this.scores;
}
}
并且,在您的 ngOnInit
内的其他组件中,您想要收听此结果:
import { Subscription } from 'rxjs';
....
export class YourOtherComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private appraisalSummaryService: AppraisalSummaryService) {}
public ngOnInit(): void {
// you store your subscribe
this.subscription = this.appraisalSummaryService.subscribe((scores: number[]) => {
console.log(scores);
});
}
public onDestroy(): void {
// you need this in order to avoid a memory leak
this.subscription.unsubscribe();
}
}
```
我有一个带有按钮的组件,单击该按钮会触发 showSummary()
,该组件会调用具有方法 calc()
Appraisal-summary.service.ts
showSummary(appraisal) {
this.summaryService.calc(appraisal);
}
有服务 Appraisal-summary.service.ts
:
calc(appraisal) {
...
//a 'scores' array is created (synchronously)
return this.scores;
}
如何侦听同步结果 this.scores
以触发将使用 scores
.[=22 的不相关组件 summary.component.ts
(已初始化)中的函数=]
类似于:
summary.component.ts
:
ngOnInit(): void {
service.subscribe(scores => this.data = scores)
}
你会想在你的 Appraisal-summary.service.ts
中添加一个 Subject
像这样:
import { Subject } from 'rxjs';
...
export class AppraisalSummaryService {
// I am guessing scores is an array of type number
public scoreSubject = new Subject<number[]>();
calc(appraisal) {
...
//a 'scores' array is created (synchronously)
this.scoreSubject.next(this.scores); //emit the scores result
return this.scores;
}
}
并且,在您的 ngOnInit
内的其他组件中,您想要收听此结果:
import { Subscription } from 'rxjs';
....
export class YourOtherComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private appraisalSummaryService: AppraisalSummaryService) {}
public ngOnInit(): void {
// you store your subscribe
this.subscription = this.appraisalSummaryService.subscribe((scores: number[]) => {
console.log(scores);
});
}
public onDestroy(): void {
// you need this in order to avoid a memory leak
this.subscription.unsubscribe();
}
}
```