【问题标题】:how to handle json stream issued by spring boot 2 in angular 5如何处理由 Spring Boot 2 以 Angular 5 发出的 json 流
【发布时间】:2018-08-10 10:56:36
【问题描述】:

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

但它对我不起作用,因为我想要反应它不会向我发送结果,因为它会缓存结果直到连接关闭

我想问在角度 5 中处理这个 Json 的最佳方法是什么

【问题讨论】:

标签: angular spring-boot jsonstream


【解决方案1】:

据我所知,仍然没有官方解决方案(19.08.2018),但是我找到了一些解决方法。 HttpClient 的每个方法都有 config 参数,您可以在其中传递 responseType 和其他内容。我混合了这些设置,如下所示:

{observe: 'events', responseType: 'text', reportProgress: true}

然后您将收到具有给定类型的事件,范围为 0 到 4。至少在我的情况下,type 3 是有趣的内容,在字段 partialText 中,但警告 - 在您的情况下,这些消息(在 @ 987654327@ 字段)将如下所示:

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());
        })
      );

【讨论】:

    【解决方案2】:

    使用服务器发送事件,可以这样做:

    import * as EventSource from 'eventsource';
    ...
    
    const eventSource = new EventSource("http://www.example.com/stream");
    
    eventSource.onmessage = (event) => {
      const data = JSON.parse(event['data']);
    }
    

    【讨论】:

    • 确保npm install @types/eventsource 避免 TypeScript 错误
    【解决方案3】:

    除了使用服务器发送事件或 WebSocket 之外,浏览器客户端无法使用 JSON 流(应用程序/流+json)。

    根据您描述的要求和技术,WebSocket 更合适。

    【讨论】:

      【解决方案4】:

      我在想的东西,也许你可以将打开的连接(get/fetch 过程)保持在一个fire and forget任务中,然后在另一个异步循环中检查是否有不同的内容而不是存储的内容来保存并展示出来。

      也许吧。

      【讨论】:

        猜你喜欢
        • 2016-11-25
        • 2021-04-17
        • 2016-12-01
        • 2017-12-17
        • 2019-10-24
        • 2019-03-01
        • 1970-01-01
        • 2018-07-11
        相关资源
        最近更新 更多