如何在TypeScript组件中使用Observable中的值Angular 4

时间:2017-09-21 21:43:44

标签: javascript angular typescript

我正在尝试从API获取JSON值并将其设置在变量中,例如:

TS

this.graphicService.getDatas().subscribe(datas => {
    this.datas = datas;
    console.log(datas);
});

test = this.datas[0].subdimensions[0].entry;

HTML

{{test}}

它在控制台上返回错误

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'subdimensions' of undefined
TypeError: Cannot read property 'subdimensions' of undefined
    at new GraphicsComponent (graphics.component.ts:33)...

但是,如果我直接在 HTML 上使用,可行

{{datas[0]?.subdimensions[0].entry}}

然后正确打印数据。 ..

1 个答案:

答案 0 :(得分:2)

试试这个:

let test;
this.graphicService.getDatas().subscribe(datas => {
    this.datas = datas;
    console.log(datas);
    test = this.datas[0].subdimensions[0].entry;
});