打字稿/角度2

时间:2017-02-20 20:48:52

标签: arrays angular typescript

private nodes = [];

constructor(private nodeService: NodeService) {}    

    this.nodeService.getNodes('APIUrl')
            .subscribe((data) => {
            this.nodes.push(data);
        });


        console.log(this.nodes)

这是我获取数据的组件。

getNodes(url) {
    return this.http.get(url)
    .map((data) => data.json())
}

这是我的服务,我可以获取数据并将其映射

但是当我在我的组件中使用console.log(this.nodes)时,这是我的结果:

[1: Array[0]]

And it is possible to see the structure of my data as shown here

所以我的问题是当我的组件中的console.log(this.nodes [0])时,我得到了未定义。我似乎无法访问我需要的数据。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

Per Juan的评论,您需要将console.log移动到回调中。

constructor(private nodeService: NodeService) {}    

    this.nodeService.getNodes('APIUrl')
            .subscribe((data) => {
            this.nodes.push(data);
            console.log(this.nodes)
        });

但实际上,您的代码表明您不了解该服务的异步性质。阅读并理解他所链接的答案。