What could be causing the undefined value of this Angular class property?

Currently, I am working on an Angular project that aims to create lobbies for various web games. The concept is to gather players through the application so that a web game can be initiated quickly.

However, I have encountered an issue where data retrieved from my Spring Boot Java API is causing problems in my Angular application. While the application successfully fetches the data, converting the observable into a normal Game[] after subscribing results in all properties of the elements becoming undefined. What could be the root cause of this problem?

The Game Service:

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

The Game 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;
    }

}

The Component:

 games: Game[];
 //Retrieve all games available in the API
    this.gameService.getAllGames().subscribe(elements => this.games = elements )
 //Unfortunately, all elements within this.games end up being undefined.

I have also attempted to use a forEach loop with the returned array, but it did not yield any positive results either.

 games: Game[];
//Retrieve all games available in 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)
      })

    })

The JSON Result for the Get Request

[
    {
        "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
    }
]

Answer №1

Your JSON response has properties starting with lowercase letters, whereas your Game class uses properties starting with uppercase letters.
It seems that the parsing from JSON to a typescript object is case sensitive. Could you attempt changing the first letter of your properties to lowercase?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to iterate through JSON object values using PHP?

How can I iterate through the values of a JSON Object in PHP? $json = '{"1":a,"2":b,"3":c,"4":d,"5":e}'; $obj = json_decode($json, TRUE); foreach($obj as $value) { echo $value; } I'm trying to display abcde, which are the values stored ...

Combining various JSON objects by nesting them together

I'm in the process of creating an endpoint where I need to combine data from four different tables into one nested object. Each table record is retrieved in JSON format using sequelize - they include information on location, service, staff, and tenant ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Having issues with your Typescript in Sublime Text?

The issue with the TypeScript plugin in Sublime Text (version 3126) suddenly arose without any identifiable cause. It seems that the plugin no longer recognizes types, resulting in disabled error highlights and autocompletions. This problem occurred on M ...

sorting an array using the selection sort technique

There is a method I found on a website that explains how selection sort works, and I want to examine its functionality: import java.util.Arrays; public class SelectionSort { public static void selectionSort(int[] data, int low, int high) { if (low &l ...

A function in Angular 2 that subscribes to an Http Observable callback

I am facing an issue with the .subscribe function in my code. Firstly, I have a function that sends a request to the server. protected sendRequest(data:string,url:string):Observable<any>{ let headers = new Headers({ 'Content-Type': &a ...

how to extract the inner elements from an array in PHP

Here is the structure of my array: array(90) { [0]=> NULL [1]=> array(1) { [0]=> string(18) "2016-03-27 0:04:06" } [2]=> array(1) { [0]=> string(1) "8" } . . . [90]=> array(1) { [0]=> ...

Parsing errors occurred when using the ngFor template: Parser identified an unexpected token at a specific column

In my Angular CLI-built application, I have a component with a model named globalModel. This model is populated with user inputs from the previous page and displayed to the user in an HTML table on the current page. Here's how it's done: <inp ...

Automate the process of triggering the "Organize Imports" command on a VSCode / Typescript project through code

Is there a way to automatically run VSCode's 'Organize Imports' quickfix on every file in a project, similar to how tslint can be run programatically over the entire project? tslint --project tsconfig.json --config tslint.json --fix I want ...

Combining JSON data in SQL Server

We are working with a base table that includes a custom column_values column called Table_Structure: User_Dimension- Userid,username,addresss,Custom_value In this structure, Userid serves as the primary key and users have the ability to map fields from th ...

Having trouble with installing the angular-4-data-table-bootstrap-4 package in NG 4.4.6 environment

I am currently working on an NG 4 project and my package.json indicates that I am using angular 4.4.6. I am attempting to include the angular-4-data-table-bootstrap-4 package as outlined below, but I keep encountering the error mentioned here that I can&ap ...

The concept of a singleton design pattern is like a hidden treasure waiting to be

My approach to implementing the singleton pattern in a typescript ( version 2.1.6 ) class is as follows: export class NotificationsViewModel { private _myService: NotificationService; private _myArray: []; private static _instance: Notificatio ...

What is the most efficient way to insert values into a multidimensional array?

Hello everyone, I am facing an issue and need some assistance. I am trying to insert values into specific array keys, but I am getting a lot of null values inserted. Here is the format I am aiming for: { "20": { "0":10, "1":20, ...

Why is my JSON object showing up as undefined in my Node.js POST request?

I have a CentOS server that is currently running a node.js HTTP server (code provided below). My goal is to pass JSON data from the command line by using the following CURL command: curl -X POST -H "application/json" -d '{"val1":"hello","val2":"my"," ...

Step-by-step guide on setting up pnpm directly, without the need to first

Here I am, faced with a brand new Windows 10 installation - only VS Code is installed and nothing more: Can pnpm be installed and used without the need for npm? Is this action beneficial or detrimental? Consideration: typescript ...

What is the best method for sending data, including the CSRF token, from an AngularJS controller to a REST controller

I have been struggling to send data from a modal using an angular controller to a REST controller. The PUT, GET, POST methods only work when CSRF is disabled, but as soon as I enable CSRF, the PUT and POST methods stop working. The console log shows 405 (M ...

The JSON output is not displaying correctly

I've been attempting to utilize JSON.stringify in order to format my json object for better readability. However, it doesn't seem to be working as expected. Can someone please offer assistance in identifying what I might have done incorrectly? ...

Retrieve a segment of text from a specific position within an array

Hello, I am new to C++ and seeking guidance on how to extract a single sentence from a paragraph stored in a string array. To clarify, let's assume myArray[2] represents the 3rd index of a string array containing multiple sentences separated by newlin ...

Two-way binding with Angular2's NgModel can encounter issues

After executing a GET XMLHttpRequest against a service, I received the following JSON payload as a response : {_id: "5aa1358d32eba9e34dd9f280", source: "Avengers", target: "Iron Man", enemies: "Actor"} Within my src/app directory, I have defined the obje ...

Looking for assistance with parsing Wikipedia JSON API in Swift

Displayed below is the json data for a WIKI page. (the formatting may not be perfect, so you can refer to this link for a better view: https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=John_F._Kennedy&pithumbsize=500) { ...