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 :
- 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.
- 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.