Reputation: 287
I am using MEAN Stack, and I am doing an asynchronous request to my mongodb database with mongoose. I now have a chart in the angular frontend, that displays some data from a mongodb query. The thing is, the data gets updated every 1 minute, and I want to automatically pull and refresh the chart every 15 minutes. Is it somehow possible to reflect this in an automatic way in mongoose? Or how would one generally realize this? I think there are different approaches:
1.I could do a http request every 15 Minutes in Angular frontend, but thats probably not good style, as I heard, http requests are observables that kind of build a socket stream to your source api, is that true?
2.If those observables keep track of changes, there is still no connection between keeping track of new data inside mongodb with mongoose and the frontend (Frontend does not know anything about new data, as the data is send from the API). I could try some kind of "push" or refresh with timer that triggers an api request and executes the api function every 1 minute or so from the backend, but I don't know how to do it as Promises are one-time triggered only and not observables... maybe this works with callbacks? How is that done in Node.js /Express and mongoose?
Upvotes: 3
Views: 1204
Reputation: 4176
I believe your best bet would be to push changes from your backend instead of relying on polling data.
The angular HttpClient just does a HTTP call when you subscribe on the observable. This results in only a single request to be performed, so there is no socket stream as you mentioned. Polling the backend every 15 minutes or so is indeed not really desirable as a much more elegant solution would be to get the changes immediately as they occur.
I believe you should look into websockets (read more) and push a notification from your backend whenever new data is ready. This would allow you do update your UI with changes immediately. You could use Socket.IO (docs) and publish a new message every time you update the database. Socket.IO is slightly easier to implement than the regular websocket API I find and will fall back to other long-polling mechanisms if websockets are not available. (further explained in this SO thread here: socket.io fallbacks. In RxJs there is a dedicated observable that you can use to subscribe to your websocket stream and receive new events pushed through your websockets: RxJs Websockets. Setting up your own observables to subscribe to your websocket events is also pretty trivial to do if you would opt to do that instead.
Upvotes: 1