我有一个AngularJs应用。在单个控制器中,我必须从3个不同的源中提取数据,并在3个不同的部分中显示数据。(在顶部、中部和底部)。每个区段中的数据将在设定的延迟内变化。对于顶部,我使用了Set interval和clear interval。对于中间部分和底部部分,我使用了$interval.For中间部分,延迟设置为7,而对于底部部分,它设置为10秒。
当我启动应用程序时,一切工作正常。但随着时间的推移,中间和底部每2秒或3秒变化一次,而不是分别为7秒和10秒。我不知道我在哪里做错了。我没有添加$interval.cancel,因为我希望中间和底部部分在7秒和10秒的延迟中连续不停止地带来数据。我还使用套接字为所有部分带来数据。我没有在“‘Destory”上使用$scope.on。我不知道这在这里是否有任何影响。下面是代码。任何帮助都将不胜感激。
socket.on('midsection', function (data) {
tableJson = [];
SplicedJson = [];
jsoninput = [];
jsoninput.push(data);
// splitting single array in to two array's so that we can display them one after the other after some delay
SplicedJson.push(jsoninput[0].splice(0, 6));
tableJson.push(jsoninput[0]);
$scope.tableData = tableJson;
//Creating interval and setting counter just to swap the json source for display
var Counter = 1;
$interval(function () {
Counter++;
if (Counter % 2 === 0) {
$scope.tableData = SplicedJson;
}
else {
$scope.tableData = tableJson;
}
}, 7000);
});
socket.on('lastSection', function (data) {
if (data.length > 3) {
array1.push(data[0]["publisher"]);
array1.push(data[1]["publisher"]);
array1.push(data[2]["publisher"]);
array2.push(data[0]["title"]);
array2.push(data[1]["title"]);
array2.push(data[2]["title"]);
$scope.msg = array1;
$scope.msg2 = array2;
$interval(function () {
data = shuffle(data); // caling custom built shuffle fn to shuffle the data to display random data everytime
console.log('Shuffled', data);
array1= [];
array2= [];
array1.push(data[0]["publisher"]);
array1.push(data[1]["publisher"]);
array1.push(data[2]["publisher"]);
array2.push(data[0]["title"]);
array2.push(data[1]["title"]);
array2.push(data[2]["title"]);
$scope.msg = array1;
$scope.msg2 = array2;
},10000);
}
});代码@ connection启动如下
io.on('connection', function (socket) {
socket.join(socket.handshake.query.room)
var entExFilepath = './midsectionData.json';
var parsedJSON = JSON.parse(fs.readFileSync(entExFilepath, 'utf8'));
fs.watchFile(entExFilepath, function () {
parsedJSON = JSON.parse(fs.readFileSync(entExFilepath, 'utf8'));
io.sockets.emit('midsection', parsedJSON);
});
io.sockets.emit('midsection', parsedJSON);
if (feedresults.length > 3) {
io.sockets.emit('lastsection', feedresults);
}发布于 2018-01-09 04:10:51
我找到了这个问题的原因。问题是,当我发送中间和最后部分的数据时,我正在执行socket.emit,这相当于在新请求到达服务器时向所有clients.So广播答案,socket.emit正在被调用并将数据发送到客户端。(这意味着每当有新的请求到来时,它也会调用内部块。因此,间隔被一次又一次地调用).I应该像下面这样做。这解决了问题。
//io.sockets.emit('lastsection', feedresults);
io.sockets.in(socket.handshake.query.room).emit('lastsection', feedresults);// This should send the data to the current client希望这对其他人有帮助
https://stackoverflow.com/questions/48127943
复制相似问题