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

4
  • 1
    Possible duplicate of Angular 2 - Return data directly from an Observable Commented Sep 21, 2017 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. Commented Sep 21, 2017 at 21:45
  • @jonrsharpe how do I do safe navigation inside TypeScript? when I just type the "?" there it does bring some errors. Commented Sep 21, 2017 at 21:48
  • Use if, or a ternary expression, or just access it from inside the subscription callback. Commented Sep 21, 2017 at 21:49

1 Answer 1

2

Try this:

let test;
this.graphicService.getDatas().subscribe(datas => {
    this.datas = datas;
    console.log(datas);
    test = this.datas[0].subdimensions[0].entry;
});
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.