gpt4 book ai didi

angular - ngFor 不显示来自 Observable 事件源的数据

转载 作者:行者123 更新时间:2023-12-04 15:53:57 25 4
gpt4 key购买 nike

在我的 Angular6 应用程序中,我在使用异步 ngfor 显示数据时遇到了问题。我期待来自后端的一些服务器发送事件(只是带有答案字符串字段的对象)。虽然 console.log 显示来自服务的答案列表包含答案,但 ngfor 不显示任何内容。

这是我的组件:

import { Component } from '@angular/core';
import { Answer } from './answer';
import { AnswerReactiveService } from './answer-reactive.service';
import { Observable } from 'rxjs';

@Component({
selector: 'app-answers',
templateUrl: './answers.component.html',
providers: [AnswerReactiveService],
styleUrls: ['./answers.component.css']
})
export class AnswersComponent {
answers: Observable<Answer[]>;

constructor(private answerReactiveService: AnswerReactiveService) {
}

requestAnswerStream(): void {
this.answers = this.answerReactiveService.getAnswerStream();
}

}

这是服务:

import { Injectable } from '@angular/core';

import { Answer } from './answer';

import { Observable } from 'rxjs';

@Injectable()
export class AnswerReactiveService {

private answers: Answer[] = [];
private url: string = 'http://localhost:8080/events/1';

getAnswerStream(): Observable<Array<Answer>> {
return Observable.create((observer) => {
let url = this.url;
let eventSource = new EventSource(url);
eventSource.onmessage = (event) => {
console.log('Received event: ', event);
const json = JSON.parse(event.data);
console.log(json);
this.answers.push(new Answer(json['answer']));
console.log(this.answers);
observer.next(this.answers);
};
eventSource.onerror = (error) => {
if (eventSource.readyState === 0) {
console.log('The stream has been closed by the server.');
eventSource.close();
observer.complete();
} else {
observer.error('EventSource error: ' + error);
}
};
});
}
}

和 HTML:

<div class="row">
<div class="col-md-8">
<p>
<button (click)="requestAnswerStream()">Gimmie answers</button>
</p>
<ul>
<li *ngFor="let answer of answers | async">{{answer.answer}}</li>
</ul>
</div>
</div>

最佳答案

经过一些研究,我通过使用 ngZone 获得了结果。我在这里发现了类似的问题:https://blog.octo.com/en/angular-2-sse-and-changes-detection/

现在我的服务代码看起来像这样并且可以正常工作:

      eventSource.onmessage = (event) => {
this.zone.run(() => {
console.log('Received event: ', event);
const json = JSON.parse(event.data);
this.answers.push(new Answer(json['answer']));
observer.next(this.answers);
});
};

我只是想知道这个解决方案是否可以被视为完全响应式的?我没有找到任何其他方法来完成这项工作。

关于angular - ngFor 不显示来自 Observable 事件源的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52655177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com