0

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

Gustavo
  • 874
  • 4
  • 13
  • 27
  • 1
    Possible duplicate of [Angular 2 - Return data directly from an Observable](https://stackoverflow.com/questions/37867020/angular-2-return-data-directly-from-an-observable) – jonrsharpe Sep 21 '17 at 21:45
  • 1
    The *whole point* of subscribing to an observable is that the data is resolved asynchronously. It will not be there immediately, but you have no "safe navigation" (the `?` in the template) in the TypeScript. – jonrsharpe Sep 21 '17 at 21:45
  • @jonrsharpe how do I do safe navigation inside TypeScript? when I just type the "?" there it does bring some errors. – Gustavo Sep 21 '17 at 21:48
  • Use `if`, or a ternary expression, or just *access it from inside the subscription callback*. – jonrsharpe Sep 21 '17 at 21:49

1 Answers1

2

Try this:

let test;
this.graphicService.getDatas().subscribe(datas => {
    this.datas = datas;
    console.log(datas);
    test = this.datas[0].subdimensions[0].entry;
});
Melchia
  • 22,578
  • 22
  • 103
  • 117
  • Cool, it worked. But now how can I use this variable as a value inside TS? for example: somedata: [ test, test2... ]. I tried this.test but it does not return as expected – Gustavo Sep 21 '17 at 22:00
  • I advise to put all the code you want to execute once the array datas is full in the subscribe method. Another solution is to create another function for the somedata and execute it with a separate event – Melchia Sep 21 '17 at 22:05