我的 Controller 中有以下内容,在 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()
}
在我的 Angular 应用程序中,我有这个:
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
最佳答案
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$;
}
}
现在多个观察者将共享相同的可观察值。
<小时/>This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
至于您的ERR_EMPTY_RESPONSE
问题。当我的代理 api 调用超时时,我就遇到了这个问题。
关于node.js - 在 Angular 中执行 Http get 方法而不重试并等待服务器发送响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48013154/