我是socket中的新手。我在现有项目中使用socket时遇到问题。我在项目中包含了socket.io.js文件,并且还创建了使用套接字的工厂。 socket请求从角度侧成功。
我想在我的API响应中更改某些内容时自动调用并在我的页面中显示结果。这是我的代码。我不知道如何用socket实现这一点
app.get('/ttms/getAlertsMessage/:customerid/:timstmp', getCookies, ttms.getAlertsMessage);// route
var socket = require('socket.io');
var io = socket.listen(server);
app.set('socketio', io);
io.on('connection', function (socket) {
console.log("==============connected=========")// this shows me connected
socket.on('test',function(data){
console.log(data)
})
});
以下是将调用的节点api:
exports.getAlertsMessage = function(req, res, next) {
var customeruuid = req.param('customerid');
var start_time = new Date().getTime(),
request = require('request'),
api_url = global.common.base_url + 'ams/1.0.0/message/customeruuid/'+customeruuid;
var _m = new cLog.mObject('DELETE', 'deleteAllVNFBackup', api_url);
request({
url: api_url,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': "Bearer " + req.cookies.apitoken
},
json: req.body
}, function(error, response, body) {
if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 202) {
res.end(JSON.stringify(body));
} else {
res.send(response.statusCode, {
"error": JSON.stringify(body)
});
});
}
这是角度服务:
GetUserSettings.getAlertsMessage($scope.customerId).then(function(data) {
var data1={"test":"test"};
socket.emit('test', data1);
socket.on('result', function (data) {
console.log(data)// gives json {"test":"test"};
});
})
任何人都可以告诉我如何实现这一点。