新版本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);
}
每一秒都会产生新的数据
{"value":"1"}
{"value":"2"}
{"value":"3"}
{"value":"4"}
{"value":"5"}
{"value":"6"}
我试过angular 5 httpclient
findAll(): Observable<Data> {
return this._http.get<Data>(this.url);
}
但它对我不起作用,因为我想响应它不向我发送结果,因为它缓存结果直到连接关闭
我想问一下在 angular 5 中处理这个 Json 的最佳方法是什么
最佳答案
据我所知,仍然没有官方解决方案 (19.08.2018),但是我找到了一些解决方法。 HttpClient
的每个方法都有 config
参数,您可以在其中传递 responseType
和其他内容。我混合了这些设置,如下所示:
{observe: 'events', responseType: 'text', reportProgress: true}
然后您将收到给定类型的事件,范围为 0 到 4。至少在我的例子中,type
3 是有趣的内容,它在字段 partialText
中,但是警告 - 在您的情况下,这些消息(在 partialText
字段中)将如下所示:
1 条消息:
{"value":"1"}
2 消息:
{"value":"1"}
{"value":"2"}
3 消息
{"value":"1"}
{"value":"2"}
{"value":"3"}
等等... 所以,我已经像下面这样管理它了:
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());
})
);
关于angular - 如何处理 Angular 5中spring boot 2发出的json流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49065527/