Stomp 客户端订阅创建新数组 javascripts
Stomp client on subscribe create new array javascripts
我正在使用 javascript Stomp 客户端在服务器发送消息时进行订阅。
需要
我需要创建一个新的订阅消息数组。每条消息都有不同的ID。如果 id 存在则不会推送任何内容,但如果数组不存在则新对象将推送到空数组。
这是我试过的
代码:
var recivedData = []
connect()
function connect() {
var socket = new SockJS('/info-app');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/info', function (msg) {
var parsedData = JSON.parse(msg.body)
if(!(recivedData.length)){
recivedData.push(parsedData)
console.log(recivedData)
}
if(recivedData.length){
if(recivedData.find(e => e.id === parsedData.id)){
console.log(" there")
console.log(recivedData)
}
if(recivedData.find(e => e.id !== parsedData.id)){
console.log("not there")
recivedData.push(parsedData)
console.log(recivedData)
}
}
console.log(recivedData)
});
});
}
问题
每当有新的id进入它就是推入数组,但是如果相同的id再次进入它也是推入。
我该如何解决?提前致谢
您不想在已将数据推入第一个空数组后执行 if(recivedData.length){
块。使用 if
语句的 else
部分:
stompClient.subscribe('/topic/info', function(msg) {
var parsedData = JSON.parse(msg.body)
if (!recivedData.length) {
recivedData.push(parsedData)
console.log(recivedData)
} else {
if (recivedData.some(e => e.id === parsedData.id)) {
console.log(" there")
console.log(recivedData)
} else {
console.log("not there")
recivedData.push(parsedData)
console.log(recivedData)
}
}
console.log(recivedData)
});
我正在使用 javascript Stomp 客户端在服务器发送消息时进行订阅。
需要
我需要创建一个新的订阅消息数组。每条消息都有不同的ID。如果 id 存在则不会推送任何内容,但如果数组不存在则新对象将推送到空数组。
这是我试过的
代码:
var recivedData = []
connect()
function connect() {
var socket = new SockJS('/info-app');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/info', function (msg) {
var parsedData = JSON.parse(msg.body)
if(!(recivedData.length)){
recivedData.push(parsedData)
console.log(recivedData)
}
if(recivedData.length){
if(recivedData.find(e => e.id === parsedData.id)){
console.log(" there")
console.log(recivedData)
}
if(recivedData.find(e => e.id !== parsedData.id)){
console.log("not there")
recivedData.push(parsedData)
console.log(recivedData)
}
}
console.log(recivedData)
});
});
}
问题
每当有新的id进入它就是推入数组,但是如果相同的id再次进入它也是推入。
我该如何解决?提前致谢
您不想在已将数据推入第一个空数组后执行 if(recivedData.length){
块。使用 if
语句的 else
部分:
stompClient.subscribe('/topic/info', function(msg) {
var parsedData = JSON.parse(msg.body)
if (!recivedData.length) {
recivedData.push(parsedData)
console.log(recivedData)
} else {
if (recivedData.some(e => e.id === parsedData.id)) {
console.log(" there")
console.log(recivedData)
} else {
console.log("not there")
recivedData.push(parsedData)
console.log(recivedData)
}
}
console.log(recivedData)
});