Angular 2 Updating objects in “real time.”

2019-03-31 02:36发布

问题:

Hi I’m trying to wrap on how to update a table angular 2.

Here is what I have: Backend: express / MongoDB. Updates are feed into the DB via an external app Data: 90% data will will be static. 10% of the data updates every second.

I’ve looked at Observables / promises. HTTP requests/ socket IO but can’t wrap my mind around the concepts.

Main Question: can I use observables with socket.io to update records?

Other Questions about data updates

  1. Angular 2’s Observables – are observables use only when the client is pulling data? or can you use it with a socket when data is being pushed to the client. (all examples online use observables with a http request)
  2. Can you use Socket IO to update an object or is it just for new objects? Every example is see is a chat application.
  3. When using http requests how do you set how often the data is requested? (some examples online use loops but that seems wrong.)

回答1:

  1. Observables are event-based so they can be used to receive events from server leveraging web sockets. Have a look at this article (section "Event-based support"):

    • https://jaxenter.com/reactive-programming-http-and-angular-2-124560.html
  2. In fact it's new objects but you can leverage the scan operators to aggregate the content of several events.

    var obs = (...)
    obs.startWith([])
       .scan((acc,value) => acc.concat(value))
       .subscribe((data) => {
         console.log(data);
       });
    

    See this question for more details:

    • Convert a plain string[] into a Observable<string[]> and concat it to another Observable<string[]> using RxJS 5
  3. If you want to pull with a time interval, you can leverage the interval method:

    Observable.interval(3000).flatMap(() => {
      return this.http.get('/some-request').map(res => res.json());
    }).subscribe((data) => {
      console.log(data);
    });