Gustavo
Gustavo

Reputation: 914

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

I'm trying to get a JSON value I got from an API and set it inside a variable, for example:

TS

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

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

HTML

{{test}}

it returns an error on console:

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)...

However, It does work if I use directly on HTML like this:

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

The data is printed correctly then. ..

Upvotes: 0

Views: 1427

Answers (1)

Melchia
Melchia

Reputation: 24314

Try this:

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

Upvotes: 2

Related Questions