Home > Enterprise >  Can't read the detail of a data
Can't read the detail of a data

Time:02-04

I like to view the details that read out from a json-file.

This is the code:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import gamejson from '../../assets/data/gametest.json';

interface GAMEDETAIL {
  id: number,
  title: string
}

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

export class GameComponent implements OnInit {

    gamedetail: GAMEDETAIL[] = gamejson;    <<<<<<----- here is the error on gamedetail
    gameid: number = 0;


    constructor(private route: ActivatedRoute) {
    }

    ngOnInit(): void {
      this.gameid = parseInt( this.route.snapshot.paramMap.get('id') as string );
    }

}

But I have this error:

Typescript: Type "{ id: number; title: string; }" is missing the following properties from type "GAMEDETAIL[]": length, pop, push, concat, and 26 more.

The json file is short

{
    "id": 1,
    "title": "Ligretto"
  }

Can you tell me, where my mistake is?

CodePudding user response:

you define gamedetail as array of GAMEDETAIL type.

gamedetail: GAMEDETAIL[] 

But then you set it as simple object:

{
 "id": 1,
 "title": "Ligretto"
}

So you need to put it in the array:

[{
 "id": 1,
 "title": "Ligretto"
}]

CodePudding user response:

type GAMEDATAIL has to be like this:

interface GameDetail {
  id: number;
  title: string;
}

and you have to declare your attribute in your component in this way:

gameDetail: GameDetail;

if you want an array of objects you need to create an array of json;

gameDetailArray: GameDetail[] = [];

and do something like this:

this.gameDetailArray.push(this.gameDetail);
  •  Tags:  
  • Related