Listening for DB data changes in Angular using Rxjs or anything

前端 未结 1 808
小蘑菇
小蘑菇 2021-01-21 08:00

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.

相关标签:
1条回答
  • 2021-01-21 08:51

    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.

    Approach with HTTP

    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.

    Alternative Approach with WebSockets

    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.

    Note about the database

    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.

    0 讨论(0)
提交回复
热议问题