【发布时间】:2018-02-20 01:52:06
【问题描述】:
我对@987654321@ 有疑问。在我的代码router.post(/comment,...) 中将用户cmets 保存在数据库中(使用猫鼬),我正在尝试emit 这个保存。在控制器功能中readMoreCourse 是从数据库中获取并显示所有cmets(并质疑如何使用socket 到这个使用ng-reapat 实时显示评论的功能)。功能AddComment 在客户端检查有效表格并将下一条评论发布到数据库。
我的问题:如何使用 angular (ng-repeat?) 和 socket.io 实时保存和显示用户评论?老实说,我是第一次做这个,我的时间很短,谢谢你的帮助。
服务器
io.on('connection', function(socket){
socket.emit('comment', function(){
console.log('Comment emitted')
})
socket.on('disconnect', function(){
})
})
API
router.post('/comment', function(req, res) {
Product.findOne({ _id: req.body._id }, function(err, product){
if(err) {
res.json({ success:false, message: 'Course not found' })
} else {
User.findOne({ username: req.decoded.username }, function(err, user){
if(err){
res.json({ success:false, message: 'Error'})
} else {
product.comments.push({
body: req.body.comment,
author: user.username,
date: new Date(),
});
product.save(function(err){
if(err) throw err
res.json({ success: true, message: 'Comment added })
**io.emit('comment', msg);**
})
}
})
}
})
})
控制器
Socket.connect();
User.readMoreCourse($routeParams.id).then(function(data){
if(data.data.success){
app.comments = data.data.product.comments;
} else {
$window.location.assign('/404');
}
});
app.AddComment = function(comment, valid) {
if(valid){
var userComment = {};
userComment.comment = app.comment;
Socket.on('comment', User.postComment(userComment).then(function(data){
if(data.data.success){
$timeout(function(){
$scope.seeMore.comment = '';
},2000)
} else {
app.errorMsg = data.data.message;
}
}));
} else {
app.errorMsg = 'Error';
}
}
$scope.$on('$locationChangeStart', function(event){
Socket.disconnect(true);
})
工厂
userFactory.readMoreCourse = function(id) {
return $http.get('/api/seeMore/' + id)
}
userFactory.postComment = function(comment){
return $http.post('/api/comment', comment);
}
.factory('Socket', function(socketFactory){
return socketFactory()
})
【问题讨论】:
-
控制器代码
Socket.on有效吗? -
基本上,如果我删除套接字部分,此代码工作正常,一切都正确保存到数据库,但现在不起作用。在控制器中不起作用,但在工厂中,例如控制台,日志显示消息
标签: angularjs express mongoose socket.io