无法在Angular2中拨打http服务?

时间:2018-07-25 06:30:41

标签: javascript json angular typescript http

嗨,我正在Angular 5中开发Web应用程序。我正在生成树状结构。我正在关注https://github.com/500tech/angular-tree-component/blob/master/example/cli/src/app/async/async.component.ts。我正在进行API调用以动态获取数据并显示为树。我的方法适用于静态数据,但不适用于在进行http调用后获取动态数据。

下面的代码适用于静态数据。

asyncChildren = [
    {
      name: 'child1',
      hasChildren: true
    }, {
      name: 'child2'
    }
  ];

 getChildren(node: any) {
    const newNodes = this.asyncChildren.map((c) => Object.assign({}, c));

    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(newNodes), 1000);
    });
  }

在上面的代码中,当我调用service而不是this.asyncChildren时,我的代码将无法工作。下面是我的实现。

getChildren(node: any) {
    const newNodes =  this.ChildTranslator().map((c) => Object.assign({}, c));
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(newNodes), 1000);
    });
  }

只要有子节点,就会调用上面的方法。因此,我代替this.asyncChildren来调用this.ChildTranslator方法,该方法进行http服务调用并获取JSON并将数据转换为所需格式。下面是ChildTranslator方法的实现。

 public string ChildTranslator(){
    this.nodeservice.GetChildNodes().subscribe(data=>{
    this.asyncChildren= this.transformer(data);
    return this.asyncChildren;
    });
}

变压器代码。

  public string transformer(data:any){

    this.asyncChildren=[];
    let results=data;
    for (const key in results) {
      if (results[key] instanceof Array) {
        const containerTyp2 = {name: '', hasChildren: false,};

        containerTyp2.name = key;
        containerTyp2.hasChildren = true;

        this.asyncChildren.push(containerTyp2);
     } else {
        const object = {name: ''};

        const containerTyp1 = {name: '', children: []};
        object.name = results[key];
        containerTyp1.name = key;
        containerTyp1.children.push(object);
        this.asyncChildren.push(containerTyp1);
    }
    this.tree.treeModel.update();
  }
return this.asyncChildren;
  }

上面的代码会弹出以下错误。

  

无法读取未定义的属性“地图”

有人可以帮助我完成这项工作吗?我可以知道以上代码中缺少的内容吗?任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

尝试:

getChildren(node: any) {

    return new Promise((resolve, reject) => {
        this.nodeservice.GetChildNodes().subscribe(data=>{
            this.asyncChildren= this.transformer(data);
            const newNodes =  this.asyncChildren.map((c) => Object.assign({}, c));
            setTimeout(() => resolve(newNodes), 1000);
        });        
    });
}

答案 1 :(得分:1)

像这样更改您的getChildren方法:

getChildren(node: any) {
    const newNodes =  this.ChildTranslator().subscribe(data=>{
    this.asyncChildren= this.transformer(data);
    this.asyncChildren.map((c) => Object.assign({}, c));
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(newNodes), 1000);
    });
   });
  }

同样,从ChildTranslator方法返回值,如下所示:

 public string ChildTranslator(){
    return this.nodeservice.GetChildNodes();
}