简体   繁体   中英

How can I update a variable using Observable without render DOM in Angular 2, like a real-time page

I am new to Angular2 + and need to create a page in real time. When I load my component, I call a service using Observable and I save the result in a variable that I use in a ngFor in my model. After loading it, I need to refresh the data every minute and need to refine the changed data.

Does anyone know how to do this?

you can start with Observable interval it will do polling for every minute.

service

poll{
     return Observable
            .interval(1000)
            .flatMap(() => {
                //ur Observable from HTTP call 
                return Observable 
            });
}

Component:- before assigning latest value try to compare values it will avoid unnecessarily assignment

   this.service.poll().subscribe(
          data => {
             // if data same don't update
              if((JSON.stringify(this.models) === JSON.stringify(data) === false) ){
 this.models = data;
} 

          }
       );

Html code

< li *ngFor="let model of models ;trackBy: trackByFn " >
{{model}}
< li >

trackBY will stop unnecessarily rendering more info https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

I think you need to combine socket.io with RxJs Observables to achieve this task

check this

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