1

This how I connect client to server with socket io.

export class OverviewService {

  socket:any;
  readonly uri:string='http://localhost:4000';

  

  constructor(private http: HttpClient) {
    this.socket = io(this.uri);
   }

and this when I call

getOnPeak(){
    this.socket.emit('on_peak/today');

    return new Observable((subscriber)=>{
      this.socket.on('on_peak/today',(data:any)=>{
        subscriber.next(data.onPeak.toFixed(2))
        console.log('onPeak:'+data.onPeak.toFixed(2));
      })
    })
    
  }

overview.ts

this.getOnPeekSub=this.overviewService.getOnPeak().subscribe(onPeak => {
      this.onPeak = onPeak;
    })

on ngOnDestroy i tried to use removeAllListeners(),removeListeners() and off() but it doesn't work .

Kilo
  • 21
  • 2

1 Answers1

0
getOnPeak(){
    this.socket.emit('on_peak/today');

    return new Observable((subscriber)=>{
      this.socket.on('on_peak/today',(data:any)=>{
        subscriber.next(data.onPeak.toFixed(2))
        console.log('onPeak:'+data.onPeak.toFixed(2));
      })

      return function unsubscribe() {
        this.socket.disconnect()
      };
    })
    
  }

When you unsubscribe from the Observalbe, the socket will be closed. Read more here https://rxjs.dev/guide/observable (Disposing Observable Executions)

enno.void
  • 6,242
  • 4
  • 25
  • 42
  • Thanks for the answer but it didn't solve the issue .This is my backend code **socket.on('on_peak/today', (message) => { setInterval(async () => { console.log('on_peak/today') socket.emit('on_peak/today', await onPeakToday()); }, 3000); });** That why client always emit when I re-reder the screen. that make heap out of memory. How to fix it? – Kilo Feb 16 '22 at 20:31