Problem with Json binding to view

#1

Hi, I am trying to bind a json to an html view, when I do the binding of an object in “foreground” like item.object works, but when I try to access another internal one like item.object.object it gives me an error, in the photo it is more clear.

when I do {{result.name}} it works

when I do {{result.games.draws}} it does not work

in the console it shows me well when I do the console.log (this.result.games.draws), any ideas?

#2

Any object (or array) property that is referenced from a template must always be feasible. If you turn strict on in your tsconfig.json, it will become a build error when you fail to do this. So if you’re going to put result.games.draws in your template, result must be initialized at a minimum to look like:

result = {games: {}};

It doesn’t matter if the full object is coming in via some other asynchronous source: a viable dummy must be assigned at construction time.

#3

but I need to access all the values, for example, with the arrays with ngFor I have no problems. I would like to have everything stored in an “object” and be able to access from any point. I’ve tried to interface with quicktype.io, but it’s the same, right?

But I do not understand why the value is correct in the variable but it is not parsed in the view. So, do you recommend me to use local variables to store the data?

this.draws = this.result.games.draws;
{{draws}}

#4

Most likely because the time you are checking it “in the variable” is not immediately at construction time, but rather once it has been populated from an asynchronous source.

I would not consider that a “local variable”, but sure, that’s one way of handling it, if you don’t want to make a dummy object like I described earlier.

Somebody else will probably come along and suggest using the ?. operator in your templates. I emphatically think they’re wrong. This is not the template’s problem. It is the controller’s job to ensure that all template-facing properties are always in a sane state.