Blog>
Snippets

Social Media Feed

Build a live social media feed, similar to Twitter's timeline, with real-time updates pushed through WebSocket to Angular application.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { WebSocketService } from './web-socket.service';

@Component({
  selector: 'app-social-media-feed',
  templateUrl: './social-media-feed.component.html',
  styleUrls: ['./social-media-feed.component.css']
})
export class SocialMediaFeedComponent implements OnInit, OnDestroy {
  feedItems: any[] = [];
  private websocketSub: any;

  constructor(private webSocketService: WebSocketService) { }

  ngOnInit(): void {
    this.websocketSub = this.webSocketService.getMessages().subscribe(
      (message: any) => {
        this.feedItems.unshift(message); // Adds new feed items to the start of the array
      },
      (err) => console.error(err),
      () => console.log('Observable completed')
    );
  }

  ngOnDestroy(): void {
    if (this.websocketSub) {
      this.websocketSub.unsubscribe();
    }
  }
}
This Angular component subscribes to a WebSocket service to receive new social media messages. It uses OnInit to start the subscription and OnDestroy to clean it up. New messages are added to the start of the feedItems array.
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';

@Injectable({
  providedIn: 'root'
})
export class WebSocketService {
  private socket$: WebSocketSubject<any>;

  constructor() {
    this.socket$ = webSocket('ws://example.com/api/feed');
  }

  public getMessages(): Observable<any> {
    return this.socket$.asObservable();
  }
}
This is the WebSocket service that creates a WebSocketSubject to connect to the server at 'ws://example.com/api/feed'. It provides a method getMessages to return an Observable of the incoming messages.