You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ngxs+WebSocket客户端如何监听Socket事件?

Ngxs WebSocket插件监听服务器事件的实现方法

核心逻辑

Ngxs WebSocket插件会将服务器推送的消息自动映射到对应的Action,你只需要定义接收消息的Action、在State中处理状态更新,最后在组件中订阅状态变化即可。


步骤1:定义接收消息的Action

根据服务器返回的消息结构,创建对应的Action类。假设服务器返回的消息格式为{ type: 'message', from: string, message: string }:

export class ReceiveMessage {
  static readonly type = '[WebSocket] 接收消息';
  constructor(public payload: { type: string; from: string; message: string }) {}
}

步骤2:在State中处理Action并更新状态

在你的State类中,添加处理ReceiveMessage Action的逻辑,将新消息存入状态:

// 定义状态模型
interface ChatStateModel {
  messages: Array<{ type: string; from: string; message: string }>;
}

@State<ChatStateModel>({
  name: 'chat',
  defaults: {
    messages: []
  }
})
export class ChatState {
  // 处理接收消息的Action
  @Action(ReceiveMessage)
  receiveMessage(ctx: StateContext<ChatStateModel>, action: ReceiveMessage) {
    const currentState = ctx.getState();
    ctx.setState({
      ...currentState,
      messages: [...currentState.messages, action.payload]
    });
  }

  // 添加状态选择器,方便组件订阅
  @Selector()
  static getMessages(state: ChatStateModel) {
    return state.messages;
  }
}

步骤3:配置WebSocket插件的消息映射(可选)

如果服务器返回的消息中,标识类型的字段不是默认的type,或者需要自定义消息转换逻辑,在插件初始化时配置deserializer:

@NgModule({
  imports: [
    NgxsModule.forRoot([ChatState]),
    NgxsWebSocketPluginModule.forRoot({
      url: 'ws://你的WebSocket地址',
      // 自定义反序列化函数,将服务器消息转为Action
      deserializer: (message) => {
        const data = JSON.parse(message.data);
        // 根据服务器消息的type字段匹配对应的Action
        switch (data.type) {
          case 'message':
            return new ReceiveMessage(data);
          default:
            return null; // 忽略未知类型的消息
        }
      }
    })
  ]
})
export class AppModule {}

步骤4:在组件中订阅状态获取消息

通过@Select装饰器或手动订阅的方式,监听State中的消息变化:

import { Component, OnInit } from '@angular/core';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { ChatState } from './chat.state';

@Component({
  selector: 'app-chat',
  template: `
    <div *ngFor="let msg of messages$ | async">
      <p>{{msg.from}}: {{msg.message}}</p>
    </div>
  `
})
export class ChatComponent implements OnInit {
  // 使用@Select订阅消息列表
  @Select(ChatState.getMessages) messages$: Observable<Array<{ type: string; from: string; message: string }>>;

  constructor(private store: Store) {}

  ngOnInit() {
    // 也可以手动订阅,做额外处理
    this.messages$.subscribe(messages => {
      console.log('最新消息列表:', messages);
    });
  }
}

额外:监听WebSocket连接状态

如果需要监听连接状态,可以直接订阅WebSocket插件内置的状态:

import { Select } from '@ngxs/store';
import { WebSocketState } from '@ngxs/websocket-plugin';

@Component({...})
export class ChatComponent {
  @Select(WebSocketState.getConnected) isConnected$: Observable<boolean>;

  ngOnInit() {
    this.isConnected$.subscribe(connected => {
      console.log('WebSocket连接状态:', connected ? '已连接' : '已断开');
    });
  }
}

内容的提问来源于stack exchange,提问作者Vinay Somawat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:31:26