Angular: 我如何从服务中的事件获取数据到我的组件?

Angular: How do I get data from an event inside a service to my component?

我目前正在编写一个 angular 项目,该项目打开与 NodeJS 服务器的 websocket 连接。这是服务:

export class WebsocketService {

  socket : any;

  constructor() { }

  setupSocketConnection(){
    this.socket = io(environment.SOCKET_ENDPOINT);
    this.socket.emit('message', 'The client wants to intruduce itself to the server');

    this.socket.on('broadcast', (data: string) => {
      console.log(data);
    });
  }

  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
    }
  }
}

这是我的组件:

export class AppComponent {
  title = '-'; 

  constructor(private websocket : WebsocketService) { }

  ngOnInit(){
    this.websocket.setupSocketConnection();
  }

  ngOnDestroy() {
    this.websocket.disconnect();
  }
}

我的问题是:如何将“数据”从广播事件侦听器传递到组件以在那里显示?另一项服务将是一种解决方案,但我认为这不是一个好的解决方案。我也可以把监听器放在一个函数中,然后从组件中调用它,但这不会违反服务的封装概念吗?

谢谢

您可以按照以下步骤使用 BehaviorSubject:

想象一下发送 JSON 包含“类型”字段的对象:确保使用

对发送的数据进行字符串化

1- 服务器端:

JSON.stringify({type: "message", value: "whatever"})

2- 现在客户端

export class WebsocketService {

  // Put the right data type here
  message = new BehaviorSubject<string>('');
  connection = new BehaviorSubject<string>('');

  socket : any;

  constructor() { }

  setupSocketConnection(){
    this.socket = io(environment.SOCKET_ENDPOINT);
    this.socket.emit('message', 'The client wants to intruduce itself to the server');

    this.socket.on('broadcast', (data: string) => {
      const jsonObject = JSON.parse(data);
      switch (jsonObject.type) {
        case "message":
          this.message.next(jsonObject.value);
          break;

        case "connection":
          this.connection.next(jsonObject.value);
          break;

        default:
          throw new Error('Unknown message type' + jsonObject.type)
          break;
      }
    });
  }

  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
    }
  }
}

另一方面,只需订阅您的数据 behaviorSubject 发出的值。

export class AppComponent implements OnInit, OnDestroy {
  title = '-'; 

  subscriptions: Subscription[] = [];
  constructor(private websocket : WebsocketService) { }

  ngOnInit(){
    this.websocket.setupSocketConnection();
    this.websocket.message.subscribe(value => {
        // Do your stuff here.
        console.log(value);
    })

    this.websocket.connection.subscribe(value => {
        // Do your stuff here.
        console.log(value);
    })
  }

  ngOnDestroy() {
    this.websocket.disconnect();
    this.subscriptions.forEach(s => s.unsubscribe());
    this.subscription = [];
  }
}