Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

node.js - Perform Http get method in Angular with no retries and wait until server sends the response?

I have the following in my controller, in a Spring-Boot application:

@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()
}

In my angular app, I have this:

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

The issue I am facing currently is that the Http get is making silent retries to the server, and as result, my expensive script is getting called 3 or 4 times. Is there an approach by which the get will make only a single request with 0 retries and wait until the script is completed and then the response should be sent back.I am calling the getData method only once. 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The http observable makes an http request for each subscriber. So the 3 to 4 http request means you must have multiple components subscribing at the same time. To share a single http request for multiple observers, you need something like the share operator.

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

Now the multiple observers will share the same observable.

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.


As for your ERR_EMPTY_RESPONSE issue. I've run into this when my proxied api call timesout.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...