Blog>
Snippets

Stock Ticker Update

Create a live stock ticker application that streams stock prices using WebSocket and updates the view in Angular without reloading the page.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { webSocket } from 'rxjs/webSocket';

@Component({
    selector: 'app-stock-ticker',
    template: ` <ul>
                  <li *ngFor="let stock of stocks">
                   {{stock.symbol}}: {{stock.price}}
                 </li>
               `}
)
export class StockTickerComponent implements OnInit, OnDestroy {
    private stockSocket = webSocket('wss://samplestockticker.com/data');
    stocks = [];

    ngOnInit() {
        this.stockSocket.subscribe(
            (data) => this.updateStockData(data), 
            (err) => console.error(err),
            () => console.log('complete')
        );
    }

    updateStockData(stockData) {
        this.stocks = stockData;
    }

    ngOnDestroy() {
        this.stockSocket.unsubscribe();
    }
}
This Angular component subscribes to a WebSocket that streams stock ticker data. When the component initializes, it subscribes to the WebSocket, and stock updates are streamed to the 'stocks' array and displayed in the view. When the component is destroyed, it unsubscribes from the WebSocket to prevent memory leaks.