为什么此Angular类属性未定义?

时间:2019-11-06 14:34:41

标签: arrays json angular typescript http

我目前正在从事Angular项目,该项目可以为不同的网络游戏创建大厅。想法是该应用程序已经吸引了玩家,因此可以立即启动网络游戏。

但是现在我遇到了一个问题,该问题是由于从Springboot Java API获取数据而引起的。 Angular应用程序正确获取了数据,但是当我在订阅课程后尝试将可观察对象转换为普通Game []时。它使Game []中元素的所有属性都不确定。 是什么原因引起的?

游戏服务:

//Returns a list of all games known to the API
  getAllGames() :Observable<Game[]>
  {
    return this.httpClient.get<Game[]>(this.connectionService.getConnectionString()+"/games",this.httpOptions)
  }

游戏类:

export class Game {
    public Id : String;
    public Name: String;
    public RedirectURI : String;
    public MinUserCount : Number;
    public MaxUserCount : Number;

    constructor(Id : String,Name : String,RedirectURI : String,MinUserCount : Number,MaxUserCount : Number)
    {
        this.Id = Id;
        this.Name = Name;
        this.RedirectURI = RedirectURI;
        this.MinUserCount = MinUserCount;
        this.MaxUserCount = MaxUserCount;
    }

}

组件:

 games: Game[];
 //Get all games known to the API
    this.gameService.getAllGames().subscribe( elements => this.games = elements )
 //This doesn't work all the elements of this.games are undefined.

我还尝试过处理返回数组的foreach。 也不起作用

 games: Game[];
//Get all games known to the API
    this.gameService.getAllGames().subscribe(elements => {
      elements.forEach(item => {
        var game = new Game(item.Id, item.Name, item.RedirectURI, item.MinUserCount, item.MaxUserCount)
        this.games.push(game)
      })

    })

GetRequest的JSON结果

[
    {
        "name": "QuizGame",
        "id": "dg217d65126b5e31v6d5v5d15v564d",
        "maxUserCount": 4,
        "redirectURI": "http://localhost:8082",
        "minUserCount": 1
    },
    {
        "name": "RPG",
        "id": "dt76TQWR127367125SDYATFHa32615",
        "maxUserCount": 10,
        "redirectURI": "http://localhost:8083",
        "minUserCount": 0
    },
    {
        "name": "Scribble Clone",
        "id": "378167e86dsahdgahkj312DJKHDg2d",
        "maxUserCount": 9,
        "redirectURI": "http://localhost:8084",
        "minUserCount": 1
    },
    {
        "name": "WebPonker",
        "id": "0o00dhsnvkjzbcxhgjyg23v2gh3dvg",
        "maxUserCount": 4,
        "redirectURI": "http://localhost:8085",
        "minUserCount": 4
    }
]

1 个答案:

答案 0 :(得分:4)

JSON响应中的属性以小写字母开头。
在您的Game类中,您使用以大写字母开头的属性。
我相信从JSON到打字稿对象的解析是区分大小写的。您可以尝试将属性的首字母更改为小写吗?