如何解决为什么不调用ReplaySubject.next导致订阅者接收新值?
我有一个服务:ScheduleService
,它拥有一个ReplaySubject<Shift>
:
private readonly shiftSubject = new ReplaySubject<Shift>();
我通过这种方法向消费者展示了这个主题:
currentShift(): Observable<Shift> {
return this.shiftSubject.asObservable();
}
我打算通过此方法将新的Shift
值推入shiftSubject
:
updateShift(shift: Shift) {
console.log('updating shift: ' + shift.shiftName); // I AM SEEING THIS LOG
this.shiftSubject.next(shift); // I'VE VERIFIED THAT THIS VALUE IS BEING UPDATED
}
但是,似乎currentShift()
的订户在调用this.shiftSubject.next(shift)
时没有收到新的发射。我已将此主题的值绑定到mat-select
组件,如下所示:
<mat-select [formControl]="shiftSelect" (selectionChange)="updateShift($event)" [value]="(scheduleService.currentShift() | async)">
<mat-option *ngFor="let shift of (scheduleService.availableShifts() | async)" [value]="shift">
{{shift.shiftName | titlecase}}
</mat-option>
</mat-select>
...而且我还订阅了这样的消耗组件,仅用于调试:
export class ShiftSelectorComponent implements OnInit,OnDestroy {
shiftSelect: FormControl;
constructor(private scheduleService: ScheduleService) {
this.shiftSelect = new FormControl();
}
ngOnInit() {
this.scheduleService.currentShift().subscribe((shift) => console.log('SHFIT SELECTOR RECEIVES NEW SHIFT: ' + shift.shiftName));
}
...
我尝试尝试执行的所有操作似乎都无法使订阅者收到更新。我不知道我在做什么错。我已经仔细检查了服务是否为单例,如other posts have mentioned that。 ScheduleService
在app.module.ts
中提供给消费者。
谢谢。
解决方法
您真的不应该公开您的服务并将其公开在模板中,每次运行更改检测时,您都会创建另一个可观察到的东西。
在组件中创建可观察对象
currentShift$ = this.scheduleService.currentShift();
availableShifts$ = this.scheduleService.availableShifts();
,然后在模板中使用它。
<mat-select [formControl]="shiftSelect" (selectionChange)="updateShift($event)" [value]="currentShift$ | async">
<mat-option *ngFor="let shift of (availableShifts$ | async)" [value]="shift">
{{shift.shiftName | titlecase}}
</mat-option>
</mat-select>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。