0

I am connecting Angular2 application having multiple states(Routes) with Node server(Socket) running on the back-end. When I visit some other state and come back to the previous state where socket code is written in service file on the angular application created with fromEvent. the service called by subscribe() in multiple components which is called in ngoninit() { } . How often I move on routes gets a component view and event emit when an event fire, So many times (multiple times) the subscribed service gets called (multiple time show console.log("get message")), which affects the performance.

    `get-messages() {
let observable = new Observable(observer => {
  this.socket = io(this.url);
  this.socket.on('message', (data) => {
    observer.next(data);    
  });
  return () => {
    this.socket.disconnect();
  };  
})     
return observable;

} `

ankur kumar
  • 419
  • 2
  • 9

1 Answers1

0

You need to end subscriptions gracefully, check out this article.

Angular/RxJs When should I unsubscribe from `Subscription`

Otherwise, how I am working with socket.io + routing is that I move the socket.io subscription to a global service. And then in components you inject the global service, which has one, uniform socket.io subscription.

Karl Johan Vallner
  • 3,980
  • 4
  • 35
  • 46