繁体   English   中英

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

[英]How to use value from Observable inside TypeScript component | Angular 4

我试图获取从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}}

然后正确打印数据。 ..

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM