在Angular中执行Http get方法而不重试,并等到服务器发送响应?

问题描述 投票:0回答:2

我的控制器中有以下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方法。 Snapshot of response from backend Snapshot of Tomcat running on port 8080 Snapshot of server response in normal case, when the script is not running Angular CLI Final Response after 189 seconds

node.js angular http spring-boot web-applications
2个回答
3
投票

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

现在,多个观察者将共享相同的观察者。

此运算符是发布的特化,当观察者的数量从零变为1时创建订阅,然后与所有后续观察者共享该订阅,直到观察者的数量返回到零,此时订阅被释放。


至于你的ERR_EMPTY_RESPONSE问题。当我的代理api呼叫超时时,我遇到了这个问题。


0
投票

最后,我弄清楚它为什么会发生这个开发服务器使用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

  }
}
© www.soinside.com 2019 - 2024. All rights reserved.