如何停止 Angular 调用 Spring webflux 流以远程关闭

How to stop Angular call to Spring webflux stream to be remotely closed

我正在学习 Spring webflux 和 Reactive Streams,并尝试了一项从 mongoDB 流式传输信息的服务。 问题是,当 MongoDB 没有任何要发送的内容时,Spring 关闭请求。 所以我真正想做的是: 在我的 mongodb 中有一个 Angular table 显示 SPRING 检索到的数据,并且每次生成 update/insert 时,新数据都会自动进入 Angular.

我找到的唯一方法是每隔 XXXX 毫秒调用我的 angular 服务。

还有其他方法吗? 所以这是我的 Spring 网络服务代码:

@GetMapping(path="/stream/organisation",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Organisation> streamAll() {
    return organisationRepository.findAll();
}

我的 Angular 服务:

getOrganisationStream(): Observable<Array<Organisation>> {
    this.Organisations = [];
    return Observable.create((observer) => {
            const eventSource = new EventSource(this.url);
            eventSource.onmessage = (event) => {
                // tslint:disable-next-line:no-console
                console.debug('Received event: ', event);
                const json = JSON.parse(event.data);
                console.log(json);
                const org: Organisation = new Organisation();
                org.codeFase = json.codeFase;
                org.id = json.id;
                org.name = json.name;
                this.Organisations.push(org);
                console.log(this.Organisations.length);
                this.ngZone.run(() => {
                    observer.next(this.Organisations);
                });
            };
            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);
            }
        };
    });
}

我的组件:

organisations: Observable<Organisation[]>;
constructor(private testService: TestService) {
}
ngOnInit(): void {
    this.organisations = this.testService.getOrganisationStream();
}

我的HTML:

   <div *ngFor="let org of organisations | async"> 
{{org.name}} {{org.codeFase}}
</div>

您将需要使用 tailable cursor 它是一个无限流,在外部关闭之前一直保持打开状态。

在您的存储库中执行如下操作:

@Tailable
Flux<Organisation> findAll();

放弃订阅时游标将关闭,在您的情况下,客户端关闭连接。