[英]how to fetch the record from mongodb to part of html page automaticalyy without refreshing/reloading manually. using MEAN stack
需要一些帮助以阅读Mean stack。 我有一个要求,
将记录插入数据库时,应在新的插入记录中显示html页面的一部分,而无需手动重新加载/刷新。
HTML页面应自动更新为新记录。
到目前为止的观察结果:我已经在使用angularjs,nodejs和mongodb。 使用refresh()函数,能够手动更新hrml页面的一部分。 我要将记录从html页面插入到mongodb。
您应该使用websockets( socket.io是一个不错的选择)。
在负责后端文档插入/更新的路由中,您应该向站点中的所有套接字发出带有文档正文的new_document
信号。
例:
app.post('/api/posts', (req, res) => { Post.insert(postBody).then(body => { io.emit('new_document', body); // Broadcast to all websocket clients res.json(body); }).catch(err => { console.error(err); res.status(500).json({error: err.message}); }); });
然后,在前端,您应该侦听new_document
事件并作为回调调用refresh()
函数,或者甚至更好的是,编写一个仅添加新文档的函数。
例:
socket.on('new_document', function (body) { // ... code to add body to HTML ... });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.