簡體   English   中英

使用angularjs和socket.io實時保存和顯示評論

[英]Save and display comment in real-time using angularjs and socket.io

我對socket.io有問題。 在我的代碼router.post(/comment,...)將用戶注釋保存在數據庫中(使用貓鼬),我正在嘗試emit此保存。 在控制器功能中, readMoreCourse是從數據庫中獲取並顯示所有注釋(以及如何使用ng-reapat實時顯示注釋來使用該函數的套接字)。 功能AddComment在客戶端chceck有效表格上,並在下一個發布注釋到數據庫。 我的問題:如何使用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.io emit事件和on事件。

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處理此問題,那么發表評論的人將有幾秒鍾的延遲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM