Malik MouSa
Malik MouSa

Reputation: 21

Angular application crashes when getting data rapidly using websockets

I am getting data from websocket nodejs backend pretty rapidly and i am showing on the frontend using *ngFor and after some time my application start lagging and eventually crash after some time. Looking for the solution.

I am looking if async can help me show changing data with *ngFor

rates.component.html

<ul>
    <li (click)="coin(coinz.type)" *ngFor="let coinz of btcCoins">
      <a href="javascript:void(0);">
        <span>
           {{coinz.symbol}}/ BTC
        </span>
        <span class="float-right">
            {{coinz.percent | number:'1.1-2'}}
            {{coinz.price}}
        </span>
      </a>
   </li>
</ul>

rates.component.ts

ngOnInit()
{
   this.socketService.getPrice().subscribe(data =>
   {
      this.btcCoins= data;
   });
}

socket.service.ts

bidask()
{
   let observable = new Observable(observer =>
   {
       this.socket = io(this.domain);
       this.socket.on('bidasks', (data) =>
       {
          observer.next(data);
       });
       return () =>
       {
          this.socket.disconnect();
       };
   });
   return observable;
}

Upvotes: 2

Views: 1569

Answers (2)

Yuri
Yuri

Reputation: 4478

When iterating over a large and partially changing collection, make sure you use trackBy.

A very straight-forward tutorial can be found at https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5

Upvotes: 1

Stephen R. Smith
Stephen R. Smith

Reputation: 3400

You could trying using the delay() operator on the Observable to slow down the rate of data being fed to the component - what may be happening is that the component is in a constant state of refresh, and eventually is overwhelmed.

bidask()
{
   let observable = new Observable(observer =>
   {
       this.socket = io(this.domain);
       this.socket.on('bidasks', (data) =>
       {
          observer.next(data);
       });
       return () =>
       {
          this.socket.disconnect();
       };
   });
   return observable.delay(100);
}

Where return observable .delay(100) is the change, and 100 is the ms delay.

Upvotes: 0

Related Questions