【问题标题】:Save and display comment in real-time using angularjs and socket.io使用 angularjs 和 socket.io 实时保存和显示评论
【发布时间】:2018-02-20 01:52:06
【问题描述】:

我对@9​​87654321@ 有疑问。在我的代码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


【解决方案1】:

在您的套接字工厂中,初始化 socket.io emiton 事件。

app.factory('socket', ['$rootScope', function($rootScope) {
  var socket = io.connect();

  return {
    on: function(eventName, callback){
      socket.on(eventName, callback);
    },
    emit: function(eventName, data) {
      socket.emit(eventName, data);
    }
  };
}]);

并从控制器调用它

app.controller('yourController', function($scope, socket) {     

User.postComment(userComment).then(function(data){  
  if(data.data.success){ 
    $timeout(function(){
      $scope.seeMore.comment = '';
      },2000); 

    // Emit new comment to socket.io server 
    socket.emit("new comment", userComment);

  } else {
      app.errorMsg = data.data.message;
  }
 });

 // other clients will listen to new events here 
 socket.on('newComment', function(data) {
     console.log(data);
     // push the data.comments to your $scope.comments    
 });

来自 socket.io 服务器

io.on('connection', function(socket) {
  // listen for new comments from controller and emit it to other clients 
  socket.on('new comment', function(data) {
    io.emit('newComment', {
      comment: data
    });
  });
});

编辑: 如果你只是想从服务器端推送,

io.on('connection', function(socket) {

    // after saving your comment to database emit it to all clients 
    io.emit('newComment', {
      comment: data
    });
});

并从控制器中删除此发射代码:

socket.emit("new comment", userComment);

但是这种方法可能很棘手,因为发布评论的用户应该会立即看到添加到帖子中的评论。如果你让socket.io 来处理这个问题,那么发布评论的人将会有几秒钟的延迟。

【讨论】:

  • 感谢您的帮助,但我对旅游代码有疑问。我可以在我的 API 中使用 socket.on('newComment', ...) 来保存产品吗?例如是否可以一次性保存到数据库,其他客户端可以监听新事件?
  • 是的,您可以这样做。只是不要从客户端发出并从服务器端推送新的 cmets。更新了我的答案。
  • 好的,谢谢,我会尝试这样做:) 所以我知道如果我从服务器端发出我的 ng-repeat 与 cmets 将自动更新如果数据库将更改
  • aaa 好的,所以如果在客户端使用 $scope.comment =[ ] 这可以防止几秒钟的延迟
  • 很酷的尝试 :) 评论可能会被添加两次,因为我们正在从服务器推送到所有客户端。
猜你喜欢
  • 1970-01-01
  • 2013-06-05
  • 2013-02-24
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 2018-12-15
  • 2021-12-04
相关资源
最近更新 更多