简体   繁体   中英

Angular2: http - actual long polling

I have a 3rd party service to implement, that provides restful API with long polling... they are serving live events, and displaying it as quick as possible is crucial.

Sadly that service does not provide push notifications, so we need to deal with what we have....

so one of the APIs has a long-polling functionality, so in theory the idea is, I query the API, establish an open channel for 30 seconds and wait for the changes... (and publish the changes on the FE)... and then timeout the connection, establish a new one and repeat the process.

Should be pretty straight forward....

But so far, I couldn't find anything in angular's docs about long polling... the only thing I found was polling in connection with rxJS... so setting an inteval on how often I query the API... (which in my case would be every 30s)... but nothing about on leaving the channel open and listen for the changes...

found this thred: How to implement http long polling in Angular 2

but it is not talking about this problem.

I don't want to end up querying the API every second.

Any ideas?

I considered implementing signalR (which might not really help here), but it relies on jQuery... which I don't want to add to the bundle unless is 100% necessary!

I think you misunderstood the concept of long-pulling.. Long-pulling where the client polls the server requesting new information. The server holds the request open until new data is available. Once available, the server responds and sends the new information. When the client receives the new information, it immediately sends another request, and the operation is repeated. This effectively emulates a server push feature.

在此输入图像描述

It you want to keep the connection alive you need to use webSoket. WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time. The client establishes a WebSocket connection through a process known as the WebSocket handshake. This process starts with the client sending a regular HTTP request to the server

在此输入图像描述

But I didn't understood from your question why you can't send another fetch request when the long-pulling completes, something like:

myLongPullingFunc(){
this.http.get(longPullingURL)
.subscribe(res=>{
  if(sholdFetchData){
    useFetchedData(res);
    this.myLongPullingFunc();
   }else
      doSomethingElse()
    })
 }

You can read more about long-pulling here and on webSokects here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM