How can I subscribe to nested JSON objects in Angular?

I am seeking advice on working with a nested JSON object. Within our server, there is an object located at "/dev/api/sportstypes/2" structured like this;

{
    "NBA": {
        "link": "https://www.nba.com/",
        "ticketPrice": 50
    },
    "UEFA": {
        "link": "https://www.uefa.com/",
        "ticketPrice": 39
    },
    "CL": {
        "link": "https://www.uefa.com/uefachampionsleague/",
        "ticketPrice": 76
    },
    "EuroLeague": {
        "link": "https://www.euroleague.net/",
        "ticketPrice": 42
    }
}

This appears to be a nested JSON object due to containing multiple smaller objects within it. The sports class structure is as follows;

export class Sports {
     link: string; //The website link of the sports association 
     ticketPrice: number; //The average ticket price for that association 
}

An attempt was made to retrieve the JSON object in the service using the following method;

getPrices():Observable<Sports[]> {
    return this.http.get<Sports[]>(sportsPath); //sportsPath corresponds to the path leading to the provided JSON data
  }

In the TypeScript file, the subscription to the object is done through this function;

sportsObject : Sports[] //This member variable needs to be populated with the JSON object

ngOnInit(){
    this.SportsService.getPrices().subscribe(data=>{
      this.sportsObject = data;
      console.log("Our member contains: " + this.sportsObject);
    })    
}

However, the console log output is "[object Object]". How can I correctly extract and subscribe to this object?

Additionally, when attempting to execute an ngFor loop in the HTML file, an error stating "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." is raised with this code;

<div *ngFor="let member of sportsObject">
       <p>The link is:</p>
       <p>{{ member.link }}</p>
</div>

How can I properly implement the ngFor loop in this scenario?

Answer №1

I think you are right in your subscription. The problem lies with the logging method. Consider using a comma instead of a plus sign.

console.log("Our member includes: ", this.sportsObject);

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

Using a basic XML file in Angular: A beginner's guide

Incorporating XML into my Angular app is a necessity. While the most straightforward approach would be to store it as a string, like so: xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + '<note>\n ...

Retrieving the value of an item within a string array using VB.NET

Here is the code snippet I am working with: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim JsonSub As String = "{""subdomain01"":[""21"",""subdomain01"",""4""],""subdomain02"":[""22"","" ...

Creating Kotlin classes to utilize Gson for converting JSON responses into class objects

I have recently delved into learning Android development, with a current focus on understanding how to consume REST API's. The particular service I am tinkering with, namely The Movie Database, returns responses structured like this: { "certi ...

A guide on utilizing Linq to read a Json file in c#

I have a JSON file with role_to_secrets for "rec" and need to retrieve the corresponding secret values for the "prod" environment. For example, if roles under "rec" are "resdns", "dnsmoon", and "resmoon", I should fetch the matching secrets for "prod": " ...

Divide and conquer- Lighttpd's mod_wstunnel combines separate messages by using UNIX socket communication to the backend server

In my experience with lighttpd's mod_wstunnel, I have encountered a peculiar issue. When I send two messages in quick succession from the backend using a UNIX socket to communicate between lighttpd and the backend, I noticed that lighttpd logs show th ...

What is preventing Typescript from inferring the type when assigning the output of a method with a return type to a variable?

My reusable service has a public API with documentation and types to make client usage easier. interface Storable { setItem(key: string, value: string): any; getItem(key: string): string; removeItem(key: string): any; } @Injectable({ providedIn: & ...

What could be causing Highlight.js to fail to work following a redirect?

After developing a small application to address a specific issue, I encountered a problem while attempting to apply code highlighting using highlight.js. The issue arises when navigating from site1 to site2 or vice versa - the highlight does not take effec ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

Developing a barrel component in React (utilizing .tsx)

My current directory structure looks like this: src assets components models counter.tsx index.ts The code found inside models/index.ts (also known as the barrel file) export * from "./counter"; The code within models/counter.ts export default in ...

Tips on incorporating esbuild extensions in the template.yaml file of AWS SAM

Currently, my TypeScript Lambda functions are managed using the AWS Serverless Application Model (SAM), and I rely on esbuild for the build process. I'm interested in incorporating esbuild plugins into my build process to enable support for TypeScrip ...

What is the best way to define an event binding statement in the Angular code rather than within the template?

Is it possible to define the event binding statement directly in the code (rather than in the template)? I am trying to dynamically create a menu, and while I can achieve this with routes (since they are strings), using event names seems to be more challe ...

What is the process for validating a JWT token using an x.509 certificate in a Node.js environment?

I need assistance with making a node script capable of validating a JWT token. I possess the public key, which is an x.509 certificate, along with the JWT itself. My attempt to utilize https://github.com/auth0/node-jsonwebtoken proved unsuccessful as it d ...

Retrieving JSON data from a URL with PHP

Attempting to retrieve JSON data from the following URL: $search_data&format=json&nojsoncallback=1 The information I am aiming to obtain based on the above link is as follows: { "places": { "place": [ { ...

Having trouble assigning an initial value to ngx-bootstrap typeahead

Hello there, I am currently using Angular version 16 with ngx-bootstrap version 11.0.2. I am facing an issue where I cannot set a default value for a control. When a user selects data from a suggestive search and it gets saved in the database, I want that ...

Implementing conditional requirements using *ngIf in Angular: A step-by-step guide

<div class="p-field-checkbox"> <p-checkbox formControlName="passwordUpdate" binary="false" name="passwordUpdate" inputId="passwordUpdate"></p-checkbox> <label for="password ...

What is the best way to arrange items by utilizing the Array index in JavaScript?

Currently, I am attempting to make the elements within this angular component cascade upon loading. The goal is to have them appear in a specific layout as shown in the accompanying image. I'm seeking guidance on how to write a function in the TypeSc ...

Transmit error notification in JSON format

In my application, I have two servlets: the first servlet acts as a client and establishes an HttpURLConnection to invoke the second servlet. My goal is to send a specific error message formatted as a JSON object. Thus, I utilize the sendError method in t ...

Nock does not capture the requests - Error: Failed to resolve address ENOTFOUND

Let me provide an overview of the structure in place. Jest is utilized for executing the testing process. Within my jest.config.json file, I incorporate the following line: "globalSetup": "<rootDir>/__tests__/setup.js", Inside setup.js, you will ...

How to remove a variable definition in Typescript

Is there a way to reset a variable to undefined after assigning it a value? To check, I am using the Underscore function _.isUndefined(). I have attempted both myVariable = undefined and delete myVariable without success. ...

The "(click)" event doesn't fire upon clicking a material icon

After creating an <a> tag with a (click) event function call, I noticed that the click event works everywhere except for the arrows mat-icons within the code snippet below: <span *ngIf="section.pages.length>0"> <mat-icon *ngIf="secti ...