Home > Software engineering >  ERROR TypeError: Cannot read properties of undefined
ERROR TypeError: Cannot read properties of undefined

Time:12-14

I am trying to get data from a component to another via service but I'm not able to get past this error :

ERROR TypeError: Cannot read properties of undefined (reading 'statistics')
    at StatsComponent_div_2_Template

I've tried multiple different implementations, for example removing the type when declaring my variable and adding the ? operator in the HTML, it removes the error but never returns anything. Can anyone tell me why please? Here is my code. Regards,

TypeScript component

export class StatsComponent implements OnInit {
  myCharactere: ICharactere = this.myService.getPersonnageByName("Xefoul Snaromers");
  statLookup = [

    { key: 'str', prefix: $localize`str`, suffix: $localize`enght`, couleur: 'bg-danger' },
    { key: 'dex', prefix: $localize`dex`, suffix: $localize`terity`, couleur: 'bg-primary' },
    { key: 'con', prefix: $localize`con`, suffix: $localize`stitution`, couleur: 'bg-warning' },
    { key: 'int', prefix: $localize`int`, suffix: $localize`elligence`, couleur: 'bg-success' },
    { key: 'sag', prefix: $localize`wis`, suffix: $localize`dom`, couleur: 'bg-info' },
    { key: 'cha', prefix: $localize`cha`, suffix: $localize`risma`, couleur: 'bg-dark' }
  ];
  constructor(public myService: ServeurService) { }

  ngOnInit(): void {
    console.log("mon perso stats", this.myCharactere)
  }
  
  getModifier(stat: number): string {
    const mod = Math.floor((stat-10)/2)
    return (mod<0)?'-':' '  mod.toString();
  }
}

HTML code

<div >
    <div >
        <div  *ngFor="let stat of statLookup">
            <div >
                <div >{{stat.prefix}}<span >{{stat.suffix}}</span>
                </div>
                <div >
                    {{getModifier(myCharactere.statistics[stat.key])}}
                </div>
                <div >
                    {{myCharactere.statistics[stat.key]}}
                </div>
            </div>
    </div>
</div>

TypeScript Service

 export class ServeurService {
  token = '';
  serverCharacter = 'https://cegep.fdtt.space/v1/characters';
  serverSecret = 'https://cegep.fdtt.space/v1/secret';
  serverToken = 'https://cegep.fdtt.space/v1/token';
  personnages: any[] = [];
  persoName = '';

  constructor(private http_client: HttpClient) { }

  setPersonnageName(name: string) {
    this.persoName = name;
  }

  getPersonnageName():string {
    return this.persoName;
  }

  getPersonnageByName(name: string) {
    const persoSelectionne = this.getPersonnages().find((n: {name: string; }) => n.name === name);
    return persoSelectionne; 
  }
}

CodePudding user response:

To fix the HTML error you can do something like this.

<div >
    <div >
        <div  *ngFor="let stat of statLookup">
            <div >
                <div >{{stat.prefix}}<span >{{stat.suffix}}</span>
                </div>
                <div >
                    {{myCharactere && myCharactere.statistics && myCharactere.statistics[stat.key] ? getModifier(myCharactere.statistics[stat.key]) : ''}}
                </div>
                <div >
                    {{myCharactere && myCharactere.statistics && myCharactere.statistics[stat.key] || ''}}
                </div>
            </div>
    </div>
</div>

Also you can initialize the myCharactere on the ngOnInit

export class StatsComponent implements OnInit {
  myCharactere: ICharactere;
  statLookup = [

    { key: 'str', prefix: $localize`str`, suffix: $localize`enght`, couleur: 'bg-danger' },
    { key: 'dex', prefix: $localize`dex`, suffix: $localize`terity`, couleur: 'bg-primary' },
    { key: 'con', prefix: $localize`con`, suffix: $localize`stitution`, couleur: 'bg-warning' },
    { key: 'int', prefix: $localize`int`, suffix: $localize`elligence`, couleur: 'bg-success' },
    { key: 'sag', prefix: $localize`wis`, suffix: $localize`dom`, couleur: 'bg-info' },
    { key: 'cha', prefix: $localize`cha`, suffix: $localize`risma`, couleur: 'bg-dark' }
  ];
  constructor(public myService: ServeurService) { }

  ngOnInit(): void {
      this.myCharactere = this.myService.getPersonnageByName("Xefoul Snaromers");
    console.log("mon perso stats", this.myCharactere)
  }
  
  getModifier(stat: number): string {
    const mod = Math.floor((stat-10)/2)
    return (mod<0)?'-':' '  mod.toString();
  }
}

CodePudding user response:

You can try nullish operator(?). because initially myCharactere is undefined. You can try this way.

            <div >
                {{getModifier(myCharactere?.statistics[stat.key])}}
            </div>
            <div >
                {{myCharactere?.statistics[stat.key]}}
            </div>
  • Related