i have a Service in backend (node.js) i am subscribing it through the angular http client service and it is working fine. for my application more than one uers are there. so some other user can change the DB data . so whenever the changes happened to DB data i would like subscribe them immediately. so all users can view the consistent data i.e., data synchronized with DB data. i am using RXJS Observables in angular services.
Before going into the answer, be aware that fulfilling your requirement is easier said than done. Implementing this for an existing infrastructure will be a lot of work and if you absolutely need to do this, it's probably better you use existing frameworks on your server-side.
HTTP is not the right kind of protocol for this task. It is request/response based and expects the client to know when it would like to request the information.
If you must use HTTP I can only think of two ways.
Option 1: Create a single HTTP request that is never closed, i.e. in express, the server never sends res.end()
or something like that. This approach requires a custom HTTP Client as well, as the default Angular HTTP Client expects the request to end before sending any notification to subscribers. However, browsers may kill off a request if no data is sent from the server, so you must implement a keep-alive yourself.
Option 2: Use "polling" - which means that you constantly ask your server if data has changed. This can be implemented in RxJS with:
interval(1000).pipe
switchMap(() => this.http.get(...)
)
This comes with the huge drawback that your server (and also your DB) has to handle a lot of requests and your network traffic increases (though only small packages are sent). However, this will probably be the easiest to implement for you as almost nothing has to be changed to support this. Be aware that your server and database will go down at some point if you have too many users at the same time.
The browser supports only so many protocols, so there are only a limited number of solutions for your requirement. One is WebSocket. It is basically the TCP protocol over the browser, but allows for long-living connections with the option for the server to push data to the client. There is even a class in RxJS for it, called WebSocketSubject
.
Now, this approach scales better than any HTTP approach, but probably requires you to rebuild huge parts of your backend. If you want to go deeper into this, you can start here.
We've only talked about network communication so far, but of course your database also has to support an observable API (except for the polling approach). You need to look into the documentation of your specific database system to find out if it does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With