簡體   English   中英

Sails.js IO.socket無法觸發

[英]Sails.js IO.socket not firing

我有一個AngularJS應用程序,試圖在數據庫中創建/刪除項目時觸發套接字觸發。 我使用自定義控制器方法('socketCreate')從使用$ resource切換到io.socket.post(),但是不確定為什么我的套接字回調都沒有觸發。

Sails JS控制台記錄新用戶,創建新用戶,angular從套接字獲取數據並刷新列表。 所有這些都可以正常運行,但是不會觸發io.socket.on回調。

我無法正確獲取eventIdentity嗎?

角度控制器:

$scope.newUser = function() {
    io.socket.post('/users/socketCreate', {name: $scope.temp_user.name}, function( data, jwres ) {
        $scope.refreshUsers();
        $scope.temp_user = {};
    });
};

if( !io.socket.newUserListen ) {
    io.socket.newUserListen = true;
    console.log( io.socket.newUserListen );

    io.socket.on( 'users', function onServerSentEvent( msg ) {
        console.log( 'users', msg );
    });

    io.socket.on( 'user', function onServerSentEvent( msg ) {
        console.log( 'user', msg );
    });
}

帆控制器:

module.exports = {
    socketCreate: function( req, res ) {
        var newName = req.param( 'name' );
        if( newName && req.isSocket ) {
            Users.create({ name: newName }).exec(function created( err, newGuy ){
                Users.publishCreate({
                    id:newGuy.id,
                    name: newGuy.name
                });
                console.log( 'User Created...' );
                res.ok( newGuy );
            })
        } else if( req.isSocket ) {
            Users.watch( req );
        } else {
            console.log( newName, req.isSocket );
        }

    }
}

未觸發事件回調的原因是,您需要訂閱Sails自動生成的會議室。 一種方法是使用Sails藍圖。 因此,如果將其添加到您的Angular控制器中,您將看到事件觸發:

 io.socket.get('/users', function(data) {});

通過發出此獲取套接字請求,您正在執行藍圖:查找操作,該操作會自動將套接字預訂到房間。 或者,您可以創建另一個使用.watch()方法執行相同操作的動作:

join: function(req, res) {
  Users.watch(req);

  return res.ok();
},

然后從控制器調用它:

io.socket.put('/users/join', function(data) {});

暫無
暫無

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

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