如何将 signalR 与 Redux-observable 一起使用?

How to use signalR with Redux-observable?

我已经创建了 Angular SPA 应用程序。我在服务器端使用 ASP.net 核心,客户端状态由 redux-observable 使用 action-reducer-epics 处理。

结构如下:我已经配置了存储、根 epics 和根减速器,然后每个组件都有自己的史诗、减速器和服务文件。

我想在 redux-observable 中容纳 signalR,但无法正确集成它。

首先将您的中心事件作为可观察对象。我改编了 this code 以对抗 ASP.NET Core SignalR。

然后创建史诗来启动集线器(我使用的是打字稿),在启动时在某处分派该操作。

const startNotificationHubEpic: Epic<RootAction, RootAction, RootState, Services> = (action$, store, { notificationHub }) => {
    return action$.pipe(
       filter(isActionOf(startNotificationHub.request)),
       switchMap(action => 
            from(notificationHub.start()).pipe(
                   map(() => startNotificationHub.success()),
                   catchError(err => of(startNotificationHub.failure(err)))
        )));
}

最后使用 startNotificationHub.success 操作开始侦听集线器上您感兴趣的每个事件的 rsjx 事件流。

const listenForMessageEpic: Epic<RootAction, RootAction, RootState, Services> = (action$, store, { notificationHub }) => {
    return action$.pipe(
        filter(isActionOf(startNotificationHub.success)),            
        switchMap(act => 
            notificationHub.on("Message", (messag: string) => ({message})).pipe(
                map(notif => onMessage(notif))
        )));
}

onMessage 操作又可以被另一个史诗使用,或者在 reducer 中用于将通知数据传递给组件。

我制作了一个小型库来使用 redux、rxjs 和 redux-observable 处理实时 SignalR (.NET Core) 事件:redux-observable-signalr-core。它无需任何额外设置即可实现自动重新连接。它非常灵活,因此您可以使用它来涵盖几乎所有场景,或者只需查看源代码即可构建您自己的解决方案。