'Socket.on in Angular

I am making a chat app with sockets and Angular, is it necessary for me to create a hidden component in the root component to listen for socket responses?Anyone help?



Solution 1:[1]

No components you would use for UI releated. You should use a service, that does this. If its needed across the whole app. You should initialize the service from the app.component.ts

edit:

Adding a fake service as example:

@Injectable({
  providedIn: 'root',
})
export class FakeWebsocketService {
  fakeWebIO: any;

  private _messages$ = new BehaviorSubject<FakeMessageExample>(null);

  // connect in app.component
  connect(connectionString: string) {
    // assming its some kind of call back class you use form websockets
    this.fakeWebIO.connect(connectionString, (message:     FakeMessageExample) => {
      this._messages$.next(message);
    });
  }
  //connect for use in component
  getReceivedMessages(): Observable<FakeMessageExample> {
    return this._messages$.asObservable();
  }
}
export interface FakeMessageExample {
  createdAt: Date;
  message: string;
  type: string;
}

in your app component ts you would then connect to the service

and in the components you need messages from the websocket you can subscribe to the messages received. This would across the whole app.

the example code is far from perfect. But its more of an example of how you could do it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1