Problem with object

Hi everyone,
I’m learning to develop with Ionic V2 and I have a problem : in my JS file I do a HTTP Request and the data is saved into a variable. When I display the variable in the console there is no problem the correct object is displayed but when I want to display an attributes of the object I have this error “Error: Uncaught (in promise): EXCEPTION: TypeError: Cannot read property ‘name’ of undefined in [{{game.name}} in GamePage@10:34]”

My JS function :

constructor(nav, http){
    this.nav = nav;
    
    this.http = http;
    this.game = null;
  
    this.http.get('http://fr.geekg.dev/Games/view/2.json').map(res => res.json()).subscribe(data => {
        this.game = data;
        console.log(this.game);
    });
}

and the object :

{
    "id": 2,
    "name": "Fallout 4",
    "serie": "FAL",
    "releaseDate": "10 Novembre 2015",
    "editor": "Bethesda",
    "developer": "Bethesda" 
}

PS : sorry for the English I’m French ^^

Your game variable is null. So what you want? )
You can use NgIf. For example:

<div *ngIf="game">{{game.name}}</div>

I don’t understand why the variable is null because I change its value during the HTTP request :confused:

Because it’s an asynchronous operation, i.e. the value is not set immediately in the constructor, as you might expect, but later after the constructor has been executed. And the template is processed before the value is set, therefore the exception. In such a case you can use the following code in the template:

{{game?.name}}

This means that the game is optional and if it’s undefined, the rest of the expression should be ignored.

I would also recommend you to check out the Angular Cheat Sheet.

3 Likes