簡體   English   中英

為什么這個 Angular class 屬性未定義?

[英]Why is this Angular class property undefined?

我目前正在開發一個 Angular 項目,該項目可以為不同的 web 游戲創建大廳。 這個想法是應用程序已經聚集了玩家,因此可以立即啟動 web 游戲。

但是現在我遇到了一個問題,這是由於從我的 Springboot Java API 獲取數據引起的。 Angular 應用程序正確獲取數據,但是當我在訂閱課程后嘗試將 observable 轉換為普通 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)
  }

游戲 class:

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
    }
]

JSON 響應中的屬性以小寫字母開頭。
在您的游戲 class 中,您使用以大寫字母開頭的屬性。
我相信從 JSON 到 typescript object 的解析是區分大小寫的。 您可以嘗試將屬性的第一個字母更改為小寫嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM