【发布时间】:2023-04-03 06:45:01
【问题描述】:
服务器node.js 每 0.5 秒更新一次数据。客户端必须轮询服务器并使用RxJS 获取新数据。我已经让客户端轮询服务器,请求已发出,但我无法读取服务器的响应。我认为由于poll_server 返回timer.pipe() 或者reducer 创建了错误的状态,所以状态没有更新。我是从老师的模板中得出的,为什么调度员会返回Observable?
model.js
export function init_state(warnings) {
return {
warnings,
accept: ({ visit_site }) => { if (visit_site) return visit_site(warnings) }
}
}
dispatcher.js
import { from, of, timer } from 'rxjs'
import { concatMap, map } from 'rxjs/operators'
import { FRONT_PAGE } from './constants'
const poll_server = url => {
return timer(0, 3000)
.pipe(concatMap(() => from(fetch(url))
.pipe(map(response => response.json())))
)
}
export const server_dispatch = action => {
switch (action.type) {
case FRONT_PAGE: {
const res = poll_server('http://localhost:8080/warnings')
console.log(res)
return res
}
default:
return of(action)
}
}
reducer.js
export function reduce(state, action) {
switch (action.type) {
case FRONT_PAGE:
console.log(`REDUCER CALLED WITH ACTION ${FRONT_PAGE}`)
return init_state(action)
default:
return state
}
}
【问题讨论】:
-
timer对poll_server的方法调用似乎返回了一个 Observable。尝试在调度程序上等待它(const res = await poll_server .....);
标签: javascript reactjs rxjs flux polling