如何在angular 5中处理spring boot 2发出的json流
Spring boot 2 WebFlux在新版本中生成Json流 比如说如何在angular 5中处理spring boot 2发出的json流,angular,spring-boot,jsonstream,Angular,Spring Boot,Jsonstream,Spring boot 2 WebFlux在新版本中生成Json流 比如说 @GetMapping(value = "stream", produces = APPLICATION_STREAM_JSON_VALUE) public Flux<Data> stream() { return Flux.interval(Duration.ofSeconds(1)).map(Data::new); } 我试过angular 5 httpclient findAll(): Obs
@GetMapping(value = "stream", produces = APPLICATION_STREAM_JSON_VALUE)
public Flux<Data> stream() {
return Flux.interval(Duration.ofSeconds(1)).map(Data::new);
}
我试过angular 5 httpclient
findAll(): Observable<Data> {
return this._http.get<Data>(this.url);
}
findAll():可观察{
返回此。_http.get(this.url);
}
但它对我不起作用,因为我希望是被动的,它不会向我发送结果,因为它会缓存结果,直到连接关闭
我想问一下,在angular 5中处理此Json的最佳方法是什么?浏览器客户端除了使用服务器发送的事件或WebSocket之外,无法使用Json流(应用程序/流+Json)
对于您描述的需求和技术,WebSocket更适合。对于服务器发送的事件,可以这样做:
import * as EventSource from 'eventsource';
...
const eventSource = new EventSource("http://www.example.com/stream");
eventSource.onmessage = (event) => {
const data = JSON.parse(event['data']);
}
据我所知,目前还没有正式的解决方案(2018年8月19日),但我找到了一些解决办法。
HttpClient
的每个方法都有config
参数,您可以在其中传递responseType
和其他内容。我混合了以下设置:
{observe: 'events', responseType: 'text', reportProgress: true}
method(url, /*if post - body,*/
{observe: 'events', responseType: 'text', reportProgress: true})
.pipe(
filter(e => e.type === 3 && e.partialText),
map(e => {
const partials = e.partialText.trim().split('\n');
return JSON.parse(partials.pop());
})
);
然后您将收到具有给定类型的事件,范围为0到4。至少在我的例子中,type
3是有趣的内容,它位于字段partialText
,但警告-在您的例子中,这些消息(位于partialText
字段)将如下所示:
{observe: 'events', responseType: 'text', reportProgress: true}
method(url, /*if post - body,*/
{observe: 'events', responseType: 'text', reportProgress: true})
.pipe(
filter(e => e.type === 3 && e.partialText),
map(e => {
const partials = e.partialText.trim().split('\n');
return JSON.parse(partials.pop());
})
);
1信息:
{"value":"1"}
2信息:
{"value":"1"}
{"value":"2"}
3信息
{"value":"1"}
{"value":"2"}
{"value":"3"}
等等。。。
所以,我像贝娄一样管理它:
{observe: 'events', responseType: 'text', reportProgress: true}
method(url, /*if post - body,*/
{observe: 'events', responseType: 'text', reportProgress: true})
.pipe(
filter(e => e.type === 3 && e.partialText),
map(e => {
const partials = e.partialText.trim().split('\n');
return JSON.parse(partials.pop());
})
);
请阅读“如何提问”:。你能告诉我们你已经试过什么吗?您希望在当前的方式中改进什么?好的,很抱歉我更新了问题@ibenjellounI我认为您应该使用WebSocket而不是HttpClient。看看本教程:确保
npm安装@types/eventsource
以避免类型脚本错误