Home > database >  ERROR TypeError: Cannot read properties of undefined (reading 'gametitle')
ERROR TypeError: Cannot read properties of undefined (reading 'gametitle')

Time:02-08

I can view the variables in the html-page but I got the error for only the value of the gametitle

ERROR TypeError: Cannot read properties of undefined (reading 'gametitle')

Here is the ts-file:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import gamejson from '../../assets/data/gametest.json';

interface GAMEDETAIL {
  id: number,
  gametitle: string,
  releasedate: number,
  description: string,
  adddate: string,
  changedate: string,
  pdffile: string,
  youtubelink: string,
  images: any,
  producer: any
}

@Component({
  selector: 'app-game',
  templateUrl: './game.component.html',
  styleUrls: ['./game.component.css']
})

export class GameComponent implements OnInit {

  private data:any = [];  
  gamedetail!: GAMEDETAIL;
  gameid: number = 0;

    constructor(private route: ActivatedRoute, private http:HttpClient) {
    }

    ngOnInit(): void {
      this.gameid = parseInt( this.route.snapshot.paramMap.get('id') as string );
      
      this.getJSON(this.gameid).subscribe(data => {
        this.gamedetail = data;
        console.log(this.gamedetail);
        console.log("gametitle: "   this.gamedetail.gametitle);
    });
    }

    getJSON(spielid: Number): Observable<GAMEDETAIL> {
      return this.http.get<GAMEDETAIL>('https://example.org/api/gamedetail/'   spielid);
    }

}

And here is the html-file, that I simple use for viewing the details

    <h1>{{ gamedetail.gametitle }}</h1>

    <p>{{ gamedetail.description }}</p>

And finally the output from the console of my browser: TheBrowserConsole

CodePudding user response:

So, this.getJSON() is asynchronous, it needs some time to get executed, in the meantime the HTML will be rendered and gamedetailis still undefined. You can avoid this error like this:

<ng-container *ngIf="gamedetail">
    <h1>{{ gamedetail.gametitle }}</h1>
    <p>{{ gamedetail.description }}</p>
</ng-container>

or

<h1>{{ gamedetail?.gametitle }}</h1>
<p>{{ gamedetail?.description }}</p>

the first approach is cleaner because the <h1> and <p> tag wont be rendered until the data is loaded. also you have the possibility to show some sort of loading animation or text in case it takes some time. <h2 *ngIf="!gamedetail">Loading...</h2>

CodePudding user response:

<h1>{{ gamedetail?.gametitle }}</h1>

<p>{{ gamedetail?.description }}</p>
  •  Tags:  
  • Related