NGXS-如何打包和操作,以便可以远程分派

时间:2020-04-08 12:50:58

标签: angular typescript ngxs

我最近正在研究多用户应用程序的对等消息传递。为此,我想到了将操作从一个客户端发送到另一个客户端的想法。

是否可以序列化一个动作?

source.connection.send(action); // the type is not in the data?

destination.connection.on("data", data => this.store.dispatch(data)) 

1 个答案:

答案 0 :(得分:0)

有官方文档,甚至还有一个插件,介绍了如何针对websockets执行此操作。


执行此操作所需的代码非常简单,所以这是我对Web套接字以外的实现。

export class SendAction {
    static readonly type = '[Connection] SendAction';
    public packedAction: any;
    constructor(action: any) {
        const type: string = action.__proto__.constructor.type;
        this.packedAction = { type: type, ...action };
    }
}

这将以一个动作作为参数,提取其类型字符串和数据,并将其存储在packedAction属性下的meta动作中。

在该状态下,您可以添加一个通过某个连接发送打包操作的处理程序:

    @Action(SendAction)
    dispatch(context: StateContext<ConnectionModel>, action: SendAction) {
        this.connection.send(action.packedAction);
    }

最后,您可以在发送方上简单地发送已发送的操作:

   connection.on('data', this.store.dispatch);

要将动作发送给客户,只需执行以下操作即可:

const action = new SomeAction("some payload");
this.store.dispatch(new SendAction(action));

请注意,我建议在此过滤操作,因为远程可以调度任何已定义的操作。