Cytsocape.js 无法创建目标不存在的边

Cytsocape.js can not create edge with nonexistant target

我尝试在使用 AJAX 请求创建节点后创建边。

我的代码:

success: function(data) {
    $.each(data['kids'], function(i, value) {
        cy.add({
            group: 'nodes',
            data: { id: value['id'] },
            position: value['position']
        });
    })
}

这有效并创建了节点。现在,我尝试使用它来创建边缘:

cy.add({
    group: 'edges', data: { id: 'e0', source: 'n0', target: 'n1' }
});

但是returns:

Can not create edge e0 with nonexistant source n0

Can not create edge e0 with nonexistant target n1

下面是我的 data 结果:

如果我使用此代码(在文档中作为示例给出),一切正常:

cy.add([
  { group: "nodes", data: { id: "n0" }, position: { x: 100, y: 100 } },
  { group: "nodes", data: { id: "n1" }, position: { x: 200, y: 200 } },
  { group: "edges", data: { id: "e0", source: "n0", target: "n1" } }
]);

我做错了什么?

我个人不会单独添加节点和边,你可以用数组保存你要添加的节点和边,然后调用cy.add():

var array = [];
// do your ajax calls
    success: function(data) {
        $.each(data['kids'], function(i, value) {
            array.push({
                group: 'nodes',
                data: { id: value['id'] },
                position: value['position']
            });
        })
    }
// add all edges
array.push({
    group: 'edges', data: { id: 'e0', source: 'n0', target: 'n1' }
});
cy.add(array);

或者您可以尝试使用 cy.ready() 来等待节点实际添加,否则可能会出现无法找到 id 的情况:

cy.ready(function () {
     cy.add({
          group: 'edges', data: { id: 'e0', source: 'n0', target: 'n1' }
     });
});

编辑:您是在 ajax 调用的内部还是外部为边缘调用 cy.add()? Ajax 是一个异步函数调用,所以成功函数之外的调用之后的所有代码可能会在您执行成功之前编写的代码之前执行。如果你愿意,你可以等待它完成并将第二个 cy.add() 放在承诺处理程序中的边缘,如下所示:

https://blog.revathskumar.com/2016/06/why-i-prefer-ajax-promise.html