我喜欢查看从json文件中读取的详细信息。
这是代码:
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 );
}
}
但我有一个错误:
Typescript:类型"{id:number;title:string;}"缺少类型"中的以下属性;GAMEDETAIL[]":长度,弹出,推动,凹入,和26更多。
json文件是短
{
"id": 1,
"title": "Ligretto"
}
你能告诉我,我的错误在哪里吗?
类型GAMEDATAIL必须是这样的:
interface GameDetail {
id: number;
title: string;
}
并且您必须以这种方式在组件中声明您的属性:
gameDetail: GameDetail;
如果你想要一个对象数组,你需要创建一个json数组;
gameDetailArray: GameDetail[] = [];
做这样的事情:
this.gameDetailArray.push(this.gameDetail);
您将游戏细节定义为GAMEDETAIL
类型的数组。
gamedetail: GAMEDETAIL[]
但你把它设置为一个简单的对象:
{
"id": 1,
"title": "Ligretto"
}
所以你需要把它放在数组中:
[{
"id": 1,
"title": "Ligretto"
}]