i want to set up a data stream between Express and Angular so that partial responses from Express can arrive and be processed in Angular without delay (when I have a piece of data, I want to send it to Angular and process it there, not waiting for the complete data). Unfortunately, the response does not make any "partial" responses, but write the information in the response and only finally sends the complete information to the frontend. But I need a continuous communication where partial information is sent to the frontend without delay. What am I doing wrong?
Express:
router.get("/getStreamedData", (request, response, next) => {
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.setHeader('Transfer-Encoding', 'chunked');
console.log("Partial response 1");
response.write("Partial answer 1");
setTimeout(function () {
console.log("Partial response 2");
response.write("Partial answer 2");
setTimeout(function () {
console.log("Partial response 3");
response.write("Partial answer 3");
setTimeout(function () {
console.log("response end");
response.end()
}, 5000)
}, 5000)
}, 5000)
});
AngularService:
getProduktdataDatastore(language: string){
let params = new HttpParams().set('language', language);
return this.http.get<any>(this.apiPath + 'getStreamedData',{params}).pipe(map(data => {console.log("data: ", data)}));
}
AngularComponent:
this.WebGridService.getProduktdataDatastore(this.selectedLanguage)
.subscribe(
response => {
console.log("responsedata: ", response)
},
error => {
this.flagLoadData = false;
this.messageBox = {messageBoxFlag: true, text: error.error} ;
}
)
Using the low-level fetch
API, you can process the response in chunks:
fetch(this.apiPath + "getStreamedData").then(function(response) {
response.body.getReader().read().then(function({done, value}) {
// value is one chunk of data
// done = true if there is no more data
});
});
See also this example .
I don't know whether the Angular http
method also produces readable streams.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.