Having trouble retrieving data from a json file using a GET request in Angular?

As a novice in dealing with json objects, I am having trouble extracting data from the GroupResult object. Below is the structure of my classes:

 export class GroupResult {
  Id!: number;
  Lecturer!: string;
  GroupName!: string;
  Subjects!: SubjectStatsStudent[];
}

export class SubjectStatsStudent {
  Id!: number;
  Name!: string;
  StudentResults!: StudentResult[];
}

export class StudentResult {
  Id!: number;
  Name!: string;
  Number!: number;
  LabPass!: number;
  LetionPass!: number;
  AllPass!: number;
  LabAvg!: number;
  TestAvg!: number;
  Rating!: number;
}

I attempted to extract the data in the following manner:

(service.ts)

import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import { Observable } from 'rxjs';
import { GroupResult } from '../model/group.results';

@Injectable({
    providedIn: 'root'
})

export class GroupService {
    getTest(): Observable<GroupResult> {
        return this.http.get<GroupResult>('../../assets/testGroup.json');
      }
}

(group.component.ts)

  ngOnInit(): void {
    this.groupService.getTest().subscribe((res: GroupResult) => this.Group = res);
    this.SelectedSubject = this.Group.Subjects[0];
  }

(testGroup.json)

{
    "Id": "777",
    "Lecturer": "Ivanov",
    "GroupName": "10701218",
    "Subjects": [
      {
        "Id": "5",
        "Name": "five",
        "StudentResults": [
          {
            "Id": "5",
            "Name": "five",
            "Number": "1",
            "LabPass": "1",
            "LectionPass": "1",
            "AllPass": "1",
            "LabAvg": "1",
            "TestAvg": "1",
            "Rating": "1"
          },
          {
            "Id": "3",
            "Name": "two",
            "Number": "2",
            "LabPass": "2",
            "LectionPass": "2",
            "AllPass": "2",
            "LabAvg": "2",
            "TestAvg": "2",
            "Rating": "2"
          },
          {
            "Id": "7",
            "Name": "tree",
            "Number": "3",
            "LabPass": "3",
            "LectionPass": "3",
            "AllPass": "3",
            "LabAvg": "3",
            "TestAvg": "3",
            "Rating": "3"
          }
        ]
      },

      {
        "Id": "7",
        "Name": "f77777e",
        "StudentResults": [

          {
            "Id": "5",
            "Name": "five",
            "Number": "1",
            "LabPass": "1",
            "LectionPass": "1",
            "AllPass": "1",
            "LabAvg": "1",
            "TestAvg": "1",
            "Rating": "1"
          },
          {
            "Id": "3",
            "Name": "two",
            "Number": "2",
            "LabPass": "2",
            "LectionPass": "2",
            "AllPass": "2",
            "LabAvg": "2",
            "TestAvg": "2",
            "Rating": "2"
          },
          {
            "Id": "7",
            "Name": "tree",
            "Number": "3",
            "LabPass": "3",
            "LectionPass": "3",
            "AllPass": "3",
            "LabAvg": "3",
            "TestAvg": "3",
            "Rating": "3"
          }
        ]
      },

      {
        "Id": "3",
        "Name": "fiv333e",
        "StudentResults": [

          {
            "Id": "5",
            "Name": "five",
            "Number": "1",
            "LabPass": "1",
            "LectionPass": "1",
            "AllPass": "1",
            "LabAvg": "1",
            "TestAvg": "1",
            "Rating": "1"
          },
          {
            "Id": "3",
            "Name": "two",
            "Number": "2",
            "LabPass": "2",
            "LectionPass": "2",
            "AllPass": "2",
            "LabAvg": "2",
            "TestAvg": "2",
            "Rating": "2"
          },
          {
            "Id": "7",
            "Name": "tree",
            "Number": "3",
            "LabPass": "3",
            "LectionPass": "3",
            "AllPass": "3",
            "LabAvg": "3",
            "TestAvg": "3",
            "Rating": "3"
          }
        ]
      }


    ]
}

However, I encountered the error:

"Cannot read property 'Subjects' of undefined"
. It seems that my Group variable is still undefined. Can someone please guide me on what mistake I might be making?

Answer №1

Attempt

initializeComponent(): void {
    this.groupService.fetchData().subscribe((result: GroupInfo) => {
        this.GroupData = result;
        this.SelectedTopic = this.GroupData.Topics[0];
    });
}

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

Tips for effectively parsing a sizable JSON document (40mb) using SWIFT

I have encountered a challenge while attempting to parse a large JSON file that exceeds the size of 40mb. Upon loading this JSON data in viewdidload(), it results in a significant memory spike up to 300mb. Are there any recommended libraries or efficient t ...

Error: Trying to access the 'title' property of an undefined variable in Vue.js

Creating a replica of hackernews by utilizing the axios API. The NewItem.vue component is not receiving any data, resulting in an error — TypeError: Cannot read property 'title' of undefined. Can you identify what's causing this issue in t ...

Documentation for npm package that has been published

Recently, I created my very first npm package using TypeScript. However, when I tried to use this package in another project, I realized that I wasn't getting the expected code completion and it was challenging to work with it without proper support. ...

Exploring the capabilities of .map alongside HTTP requests in Angular 2

I'm curious to know if the use of .map is necessary when making API calls with http in Angular 2. Take a look at my code below. It seems to work both with and without .map. If the API returns data, it signals success; otherwise, it indicates an err ...

Guide on retrieving image file name and extension with camera plugin in Ionic 2

Hi everyone, I'm looking for a way to retrieve the image name with its extension using the camera plugin in Ionic 2. Any tips on how to achieve this? Thank you! Below is the code I have so far: // Function for selecting an image ImagePick() { ...

Creating JavaScript Objects from HTML Form data with the help of serializeJSON

Struggling extracting HTML form data into the required JSON format for server communication. Despite following a guide, I can't get the output right. Managed to extract question keys and values, but labeling is tricky. Current Output: {"Question1":" ...

Error: nvm command not found

I downloaded nvm for windows and successfully installed two versions of nodes by following the steps provided in this article. https://medium.com/appseed-io/how-to-run-multiple-versions-of-node-js-with-nvm-for-windows-ffbe5c7a2b47 The node versions I hav ...

When trying to retrieve the Unix time in milliseconds using the MongoDB Timestamp Output Format, it returns an object labeled "$numberLong" instead

I am currently working on a Spring Application that stores JSON data in MongoDb. Users can search for specific data by entering a time interval start and end. To enable the use of regex (lte and gte) for filtering data from the database, I store the Time a ...

What are the repercussions of labeling a function, TypeScript interface, or TypeScript type with export but never actually importing it? Is this considered poor practice or is there a potential consequence?

I find myself grappling with a seemingly straightforward question that surprisingly has not been asked before by others. I am currently immersed in a TypeScript project involving Vue, and one of the developers has taken to labeling numerous interfaces and ...

Parsing JSON data using JSON.NET

Previously, I had successfully obtained the answer using silverlight's System.JSON. However, due to updated specifications, I now need to achieve the same result in .NET 3.5. This is the JSON data that I am currently receiving: {"SearchResults":[{"P ...

'The condition 'NgIf' does not fall under either 'ComponentType' or 'DirectiveType' category

Encountering an error when using *ngIf in a basic component is quite puzzling. This particular issue seems to be triggered by the following code and app.module setup: app.component.html: <ng-container *ngIf="true"> <div>True</di ...

Strategies for preventing profanity in Typescript within Nuxt 2 implementation

implement user authorization functionality create the Auth class for authentication handling import type { Context } from '@nuxt/types'; export class Auth { public ctx: Context; constructor(ctx: Context) { t ...

Using a JSON file as a database for a project featuring HTML, CSS, and Vanilla JavaScript

Our task was to create a project that exclusively utilized JSON files for data storage. The data structure we were working with resembles the following: [ { "aircraftName": "Boeing 747", "departDate": 1640173020000, ...

Discrepancy in Gson behavior between generated APK and debug mode

My current task involves parsing data received from a notification bundle: String intervalsData = data.getString(ARG_INTERVAL, "[]"); Type intervalListType = new TypeToken<List<Interval>>() {}.getType(); List<Interval> intervalList = Con ...

Using node.js to iterate through unspecified objects

I am facing the challenge of working with a directory of files generated by a service, where each file lacks an extension. Here are some examples of file names: all_events_20170406v1 all_events_20170406v2 These files contain multiple JSON objects without ...

NextJS: Error - Unable to locate module 'fs'

Attempting to load Markdown files stored in the /legal directory, I am utilizing this code. Since loading these files requires server-side processing, I have implemented getStaticProps. Based on my research, this is where I should be able to utilize fs. Ho ...

What is the best way to display both keys and values from a JSON object containing dictionaries and lists?

I'm a beginner in Python and have a basic understanding of working with lists and dictionaries. However, I'm facing difficulties in extracting the required JSON values when making an API call. Specifically, I am trying to retrieve the values for ...

Converting a JSON file into an HTML table using PHP

I need help figuring out how to display JSON data in an HTML table. I have a script that successfully outputs my JSON content, but I'm struggling to format it into a table. Below is the code I have so far: <?php $dir = "/Apache24/htdocs/reservat ...

Tips for configuring TypeScript in a monorepo to successfully compile private packages

I have configured a monorepo using turborepo that includes Nestjs for the backend and Nextjs for the frontend. To reuse prisma definitions, I separated them into their own package with its own tsconfig. In the index file of my database package where prism ...

Using Python to pass a JSON file as input for an API request

Recently delving into Python, I've encountered a challenge in writing a script that takes a JSON file and sends its contents to an API. I've refrained from using json.dumps() due to concerns raised in the documentation about the JSON not being co ...