0

For learning purposes, I would like to stream data from my Spring back-end and collect collect items in a front-end using angular as soon as items are added to the stream ( item by item ) .

The problem I have is :

  1. If I call the backend url directly from a browser, I can see the items displayed one after one with the interval of 250ms that I have set on the backend for the example.
  2. But, I cannot manage to have the same behavior with Angular, The Observable seems to receive only one big Response when all the data / items are put in the stream. my goal is to collect and display the items one by one as soon as they are added to the stream.

Here is my backend endpoint (Spring boot) :

    // import reactor.core.publisher.Flux;

    @GetMapping(value = "/data/stream", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<String> streamDataArray() {
        String [] array  = new String[20];
        for(int i=0;i<array.length; i++){
            array[i] = i+1+"" ;
        }
        return Flux.fromArray(array).map(s->{
            try {
                Thread.sleep(250L);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
            return s;
        });
    }

In the front-end side (Angular) I created a service method that uses HttpClient and returns an Observable over the stream :

export class StreamingService {

  constructor(private httpClient: HttpClient) { }

  getStream(): Observable<string[]>{
    return this.httpClient.get<string[]>(`/api/data/stream/`);
  }

}

And a component I have a method that subscribes to the Observable. The method is invoked when I click on a Button :

 getStream() {
    this.streamingService.getStream()
      .subscribe(
        {
          next(item) {
            console.log(item);
          },
          error(msg){
            console.error(JSON.stringify(msg));
          },
          complete(){
            console.log('Observable completed')
          }
        }
      );
  }

Is my understading correct ? What I am missing ? thanks.

Mehdi
  • 1,340
  • 15
  • 23
  • You need more just than a simple GET call. See https://stackoverflow.com/a/62057926/3359635 – mat.hudak Oct 07 '21 at 05:02
  • When you want to push events from server to client (in this case the browser) you need one of the following technologies: long polling (maintain an HTTP connection opened in the server), Server Sent Events aka SSE (unidirectional communication, this API is provided by the browser and maintains an HTTP connection for you) and WebSockets aka WS (bidirectional communication). – Nico Oct 08 '21 at 06:51

0 Answers0