【问题标题】:Function always execute before response comes from nested function函数总是在响应来自嵌套函数之前执行
【发布时间】:2020-03-10 23:03:36
【问题描述】:

我有 function1(),当我调用 function1 时 response.hasOwnProperty('xxx') 总是假的

function1() {
    let value1 = this.findTreeByNode({ nodeUuid: this.cart.selectedNodeUuid })

…… 这里我需要 findTreeByNode() 返回的 value1 的值 ......

  }
}

这是调用后端的 findTreeByNode() 函数

   findTreeByNode(node: any, isSearch: boolean = false)  {

    return this.treeService.getParentList(node).subscribe(res => {
        this.topNodes.forEach((topNodes, treeIndex) => {
          if (res.data.length > 0) {
            if (topNodes.nodeUuid === res.data[0].nodeUuid) {
              res.treeIndex = treeIndex;
            }
          }
        });
        return res;
      });
    }

问题是 **function1 () ** 总是在响应来自内部后端调用函数之前执行。这两个功能都在同一个组件中。 function1 的嵌套函数具有 backend 调用并订阅 observable。 我试图让函数 findTreeByNode () 返回可观察的,所以我可以订阅 function1,但不工作。 我想执行“让响应= ....”仅在函数返回某些内容后执行。

【问题讨论】:

  • 能否提供完整的代码组件(没有不必要的部分)
  • 如果你不会到处返回anytype,我相信你会发现你的错误。
  • 使用从 findTreeByNode() 函数的 of(res) 中返回 observable

标签: angular typescript rxjs


【解决方案1】:

我会从你的 findTreeByNode 函数中删除订阅。这允许您在实际收到响应后处理从订阅中返回的对象。使用您的示例,类似于以下内容:

function1() {
  if (!this.cart.entitlementsObj.ekey_view_tree) {
    this.treeService.getParentList({ nodeUuid: this.cart.selectedNodeUuid }).subscribe(
      (res: any) => {
        const response = this.findTreeByNode(res);
        if (response.hasOwnProperty('treeIndex')) {
          this.componentRef[response.treeIndex].instance.hideTree();
        }
      }
    );
  }
}

findTreeByNode(res: any, isSearch: boolean = false) : any {
  res.treeIndex = 0;
  this.topNodes.forEach((topNodes, treeIndex) => {
    if (res.data.length > 0) {
      if (topNodes.nodeUuid === res.data[0].nodeUuid) {
        res.treeIndex = treeIndex;
      }
    }
  });
  return res;
}

【讨论】:

    猜你喜欢
    • 2013-11-05
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多