【问题标题】:Displaying APPLICATION_STREAM_JSON object in Angular throws error在 Angular 中显示 APPLICATION_STREAM_JSON 对象会引发错误
【发布时间】:2018-02-18 13:36:35
【问题描述】:

您好,我创建了一个新的Spring Boot 2.0 应用程序,基于WebFlux。所以我有一个方法,它每 5 秒产生 APPLICATION_STREAM_JSONInterval。它看起来像:

public Mono<ServerResponse> findAllPeople(ServerRequest serverRequest) {
    Flux<Person> personFlux = personRepository.findAll();
    return ServerResponse.ok().contentType(MediaType.APPLICATION_STREAM_JSON).body(personFlux, Person.class);
}

基本上我想用最新的Http Client module 将它附加到Angular 4 应用程序。现在我正在努力解决一个错误,上面写着:

error: SyntaxError: Unexpected token { in JSON at position 49 at JSON.parse 
text:
"{"id":1,"name":"JAN","surname":"NOWAK","age":10}↵{"id":2,"name":"ADAM","surname":"KOWAL","age":20}↵"

如您所见,我得到了两个JSONs,我想在浏览器中公开它。我知道错误是什么意思,但是当我将MediaType 更改为常规Application JSON 时,它怎么可能正常工作?

在前端我有一个组件:

export class AppComponent implements OnInit {
  constructor(private http: HttpClient) {
  }
  title = 'app';
  dataGet: any;


  ngOnInit(): void {
    this.getData();
  }

  getData() {
    this.http.get('http://localhost:8080/api/person').subscribe((res => {
      console.log('------', res);
      this.dataGet = res;
    }));
  }

然后我显示它

<H1>Data get</H1>
<div *ngFor="let d of dataGet">
  {{d.id}}
  {{d.name}}
  {{d.age}}
</div>

【问题讨论】:

    标签: angular rx-java reactive-programming spring-webflux


    【解决方案1】:

    我猜"application/stream+json" 媒体类型对于服务器到服务器的通信很有用,而浏览器不知道如何解析它:它似乎不明白它应该单独考虑每个 JSON 对象并在新行上拆分。

    对于服务器到浏览器的通信,"text/event-stream"(又名 SSE)可能是更好的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多