我对 Angular (10) 相当陌生,并试图掌握 Observables 的概念。我有一个服务和一个组件,服务用参与者填充一个数组,并且组件应该显示它们
服务
export class MercureService {
private _participants = new BehaviorSubject<ParticipantDTO[]>([]);
private participantList: Array<ParticipantDTO> = [];
constructor() {
}
get participants$(): Observable<Array<ParticipantDTO>> {
return this._participants.asObservable();
}
admin_topic(topic: AdminTopic): void {
const url = new URL(environment.mercure);
url.searchParams.append('topic', `${topic.sessionUuid}_${topic.userUuid}`);
const eventSource = new EventSource(url.toString());
eventSource.onmessage = event => {
const json = JSON.parse(event.data);
console.log('NEW EVENT');
// ...
if (json.event === BackendEvents.NEW_PARTICIPANT) {
this.participantList.push({voter: json.data.voter, voterUuid: json.data.voterUuid, vote: '0'});
this._participants.next(this.participantList);
}
};
}
组件.ts
export class StartSessionComponent implements OnInit, OnDestroy {
// ...
unsubscribe$: Subject<void> = new Subject<void>();
participantList: ParticipantDTO[];
constructor(
// ...
public mercure: MercureService
) {}
ngOnInit(): void {
this.mercure.participants$
.pipe(takeUntil(this.unsubscribe$))
.subscribe((data) => {
this.participantList = data;
});
this.mercure.admin_topic({sessionUuid: '123', userUuid: '456'});
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
组件.html
...
<div *ngFor="let participant of this.mercure.participants$ | async">
<p>{{participant.voter}} - Vote ({{participant.vote}})</p>
</div>
...
所以我没有发送消息,它被 EventSource 接收,console
说
NEW EVENT
并且 UI 得到更新(添加一个新的<p>WHATEVER NAME - VOTE XXX</p>
)。但是,当我从服务器发送第二条消息时,我得到
NEW EVENT
再次,但 UI 没有得到更新。我怀疑我对 Observable 做错了什么,有人可以帮忙吗?