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';

  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 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';

  providedIn: 'root'
export class WebSocketService {
  private socket$: WebSocketSubject<any>;

  constructor() {
    this.socket$ = webSocket('ws://');

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