angular - 如何处理 Angular 5中spring boot 2发出的json流

标签 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);
}

每一秒都会产生新的数据

{"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/

相关文章:

spring-boot - Paypal REST API 返回 INVALID_CURRENCY_AMOUNT_FORMAT

node.js - 读取大型 JSON 文件的最佳方式

javascript - 处理太大而无法放入内存的 JSON 对象

angular - 如何只在需要时加载 Zone.js

typescript - 如何为在 ag-grid 单元格渲染中动态创建的按钮引发事件?

spring - 如何通过特定主体名称删除现有 session

json - 如何使用流对 Node.js 中的大型嵌套对象进行 JSON 字符串化?

javascript - ngOnInit 外部的函数调用 ngOnInit 内部的函数

forms - 在 Angular2 : What is the proven way? 中的多步骤表单之间交换数据

postgresql - 创建指向现有实例的 bluemix postgresql 服务