How to implement http long polling in Angular 2

2019-07-31 11:31发布

问题:

I have a use case as follows:

  • User selects a video to be uploaded to their profile.
  • Angular sends a request to node.js server which returns an Amazon S3 pre-signed URL.
  • Browser 'directly' uploads the file to S3.
  • Elastictranscoder kicks in to transcode the video.
  • AWS-SNS follows an https endpoint to inform the node.js back-end of transcoding's completion.

How to reflect this fact that the video is now available on the Angular side?

I'm doing something similar to the following and it is working fine, but I'm not so sure if the error-case is being handled correctly? Should I be doing anything more?

 startLp(): Observable<any> {
   return this.http
     .get("/getvideostatus?video-id=blah", { headers: this.headers })
     .map(res => {
       return res.json();
     })
     .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}

This is just a regular http request, the only difference is the server not returning the response immediately.

Would this constitute a valid http long poll?

回答1:

This is what I ended up doing:

public startLp(): Observable<any> {
let that = this;
let doLp = function(): Observable<any> {
  return that.http
    .get("/getvideostatus?video-id=blah", { headers: that.headers })
    .map(res => {
      return res.json().data
    })
    .catch((error: any) => {                    
      return doLp();
    });
};

return doLp();
}