簡體   English   中英

在 Angular 中執行 Http get 方法而無需重試並等待服務器發送響應?

[英]Perform Http get method in Angular with no retries and wait until server sends the response?

我的控制器中有以下內容,在 Spring-Boot 應用程序中:

@RequestMapping(method=RequestMethod.GET,value="/info")
public DataModel getinfodata()
{
    //this method runs some script which takes more than 3 minutes and sends the response back
    return run_xyz()
}

在我的角度應用程序中,我有這個:

export class FetchService {
  private _url:string="/info";
    constructor(private _http:Http) { }
    getData():any
    {
      return this._http.get(this._url).map((res:Response)=>res.json()).
        catch(this.errorHandler).subscribe(data=>console.log(data));
    }
    errorHandler(error: Response){
      console.error(error);
      return Observable.throw(error || "Server Error");
    }

我目前面臨的問題是 Http get正在對服務器進行靜默重試,因此,我的昂貴腳本被調用了 3 或 4 次。 是否有一種方法可以讓get只發出一個請求並重試 0 次,然后等待腳本完成,然后應該發回響應。我只調用 getData 方法一次。 來自后端的響應快照在端口 8080 上運行的 Tomcat 的快照正常情況下服務器響應的快照,當腳本未運行189 秒后的Angular CLI最終響應

http observable 為每個訂閱者發出一個 http 請求。 所以3到4個http請求意味着你必須有多個組件同時訂閱。 要為多個觀察者共享單個 http 請求,您需要類似share運算符的東西。

export class FetchService {
    data$: Observable<any>;

    constructor(){
        this.data$ = this._http.request(this._url)
            .map((res:Response)=>res.json())
            .catch(this.errorHandler)
            .share();
    }

    getData(){
        return this.data$;
    }
}

現在多個觀察者將共享同一個觀察者。

這個操作符是publish 的一個特化,它在觀察者的數量從0 變到1 時創建一個訂閱,然后與所有后續觀察者共享該訂閱,直到觀察者的數量歸零,此時訂閱被處理。


至於你的ERR_EMPTY_RESPONSE問題。 當我的代理 api 調用超時時,我遇到了這個問題。

最終,我弄清楚了為什么會發生這種情況 dev-server 使用http-proxy-middleware package More Here並且該包中提供的代理選項來自底層http-proxy library http-proxy options 其中之一是

代理超時

代理沒有收到響應時的超時(以毫秒為單位)

如果服務器未能在規定的時間(120 秒)內響應,則默認值為 ~120 秒(根據我的觀察)向服務器發出新請求。 在代理配置文件中使用"timeout":30000覆蓋默認超時解決了該問題。

{
  "/info": {
     "target":  {
       "host": "localhost",
       "protocol": "http:",
       "port": 8080
     },
     "secure": false,
     "changeOrigin": true,
     "logLevel": "debug",
     "timeout":30000
  
  }
}

暫無
暫無

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

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