2017-09-11 1 views
0

socket.io에 문제가 있습니다. 내 코드 router.post(/comment,...)에서 사용자 의견을 데이터베이스에 저장하고 (몽구스 사용) emit이 저장됩니다. 컨트롤러 기능에서 readMoreCourse은 데이터베이스의 모든 주석을 가져와 표시하는 것입니다 (그리고 ng-reapat를 사용하여 실시간으로 주석을 표시하는이 함수에 소켓을 사용하는 방법에 대해 질문하십시오). 기능 AddComment은 클라이언트 쪽 chceck 유효한 양식과 데이터베이스에 대한 다음 게시물 주석에 있습니다. 내 질문 : 실시간 저장 및 표시 각도 (ng-repeat?) 및 socket.io 사용하여 사용자 의견을 표시하는 방법? 솔직히 나는 이것을 처음 만들었고 어떤 도움을 주셔서 감사합니다.angularjs 및 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() 
}) 
+0

컨트롤러 코드 'Socket.on'이 작동합니까? –

+0

기본적으로 소켓 부분을 제거하면이 코드가 제대로 작동하지만 모든 것이 데이터베이스에 저장되는 것이 적절하지만 지금은 작동하지 않습니다. 컨트롤러가 작동하지 않지만 공장에서 작동 중입니다. 콘솔, 로그에 메시지 표시 –

답변

1

소켓 팩토리에서 socket.io emiton 이벤트를 초기화하십시오. socket.io 서버에서 컨트롤러

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  
}); 

에서이

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); 
    } 
    }; 
}]); 

및 전화

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을 보내면 코멘트를 게시 한 사람에게 몇 초 지연 될 것입니다.

+0

도움 주셔서 감사합니다.하지만 코드를 둘러 보는 데 질문이 있습니다. 내 API에서 제품 저장과 함께 socket.on ('newComment', ...)을 사용할 수 있습니까? 예를 들어 한 번에 데이터베이스에 저장할 수 있으며 다른 클라이언트는 새 이벤트를들을 수 있습니까? –

+0

네, 그렇게 할 수 있습니다. 클라이언트 측에서 내 보내지 말고 서버 측에서 새로운 코멘트를 푸시하십시오. 내 대답이 업데이트되었습니다. –

+0

그래, 고마워, 내가 그것을 시도 할 :) 나는 서버 측에서 내 ng-repeat를 보내면 주석이있는 데이터베이스가 바뀌면 자동으로 업데이트된다는 것을 이해한다. –

관련 문제