簡體   English   中英

如何以快速和角度流式傳輸響應?

[英]How do I stream response in express and angular?

我想在 Express 和 Angular 之間建立一個數據流,以便來自 Express 的部分響應可以立即到達並在 Angular 中處理(當我有一條數據時,我想將它發送到 Angular 並在那里處理它,而不是等待為完整的數據)。 不幸的是,響應並沒有做出任何“部分”響應,而是將信息寫入響應中,最后才將完整的信息發送到前端。 但是我需要持續的通信,其中部分信息會立即發送到前端。 我究竟做錯了什么?

表達:

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)

});  

角服務:

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

角組件:

          this.WebGridService.getProduktdataDatastore(this.selectedLanguage)                   
            .subscribe(
              response => {
                console.log("responsedata: ", response)
              },
              error => {
                this.flagLoadData = false; 
                this.messageBox =  {messageBoxFlag: true,  text: error.error}  ;
              } 
            ) 

使用低級fetch API,您可以分塊處理響應:

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

另請參閱此示例

我不知道 Angular http方法是否也產生可讀流。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM