utilize TypeScript to iterate through an array in a JSON object

How can I loop through the subjects array in a JSON response?

JSON Response:

{
    "$id": "1",
    "Council_ID": 116,
    "number": "67",
    "subjects": [
        {
            "$id": "2",
            "subjectCode": "67",
            "type": 4,
        },
        {
            "$id": "3",
            "subjectCode": "67",
            "type": 4,
        }
       ]
    }
    

model.component.ts:

this.dataStorageService.storeSubjects(newSubject, this.meetingID)
            .subscribe(
            response => {
                this.dataStorageService.getCouncilId(this.meetingID).subscribe(response => {
                    this.subjectsWithID = response.json();
                    this.sublength = this.subjectsWithID.subjects.length;
                    console.log(this.sublength);
                    for(let i = 0 ; i <= this.sublength; i++){
                        this.typee = this.subjectsWithID.subjects[i].type;
                        this.dataStorageService.getSubjectTypeId(this.typee).subscribe(response =>{
                            this.namesOfSub = Array.of( response.json());
                            console.log(this.namesOfSub)
                        });
                    }
                    // console.log(this.typee, 'bla bla');
                });
                this.addSubjectForm.reset();
                this.router.navigate(['/model']);
                return true;
    

How can I fix the error: "Property 'subjects' does not exist on type 'any[]'. Is there any suggestion to get rid of this error?

Answer №1

When utilizing httpClient, it is not possible to directly access the property this.subjectsWithID.subjects. However, by using http, it can be achieved. This is because httpClient lacks the ability to determine the structure of your object when parsing the result. To access your property, you need to specify a type for your result or access it using bracket notation:

this.subjectsWithID['subjects']

Another way to handle this issue is by specifying the type using an interface:

return this.http.get<myObject>(...url)

interface Sidebar {
    id: number;
    Council_ID: number,
    number: number,
    subjects: [...
}

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

How do I manage two components on the same routing level in Angular with query parameters?

I am working with Angular and have two components placed at the same level of routing, both in the root directory. { path: '', component: HomeComponent }, { path: '', component: SearchComponent }, My challenge is to mak ...

An alternative to the JsonConstructor attribute in Json.Net for System.Text.Json

Json.Net provides the JsonConstructor attribute to direct the deserializer to use a specific constructor for object creation. Are there any equivalent features available in System.Text.Json? ...

How is it that TypeScript still expects a valid return from an overridden method, even when it cannot be reached?

After creating a generic RESTClient with some abstract functions, I encountered an issue where not all REST actions are implemented. In these cases, I wanted to throw an error. The problem arose when trying to override the TypeScript method to both return ...

This error occurs because the argument type 'AsyncThunkAction<any, void, {}>' cannot be assigned to a parameter of type 'AnyAction'

I encountered an error that I couldn't find a solution for on Stack Overflow The argument of type 'AsyncThunkAction<any, void, {}>' is not compatible with the parameter of type 'AnyAction'. <MenuItem onClick={() =&g ...

Mastering Angular 7: A guide to efficiently binding values to radio buttons

Struggling to incorporate radio buttons into my project, I encountered an issue where the first radio button couldn't be checked programmatically. Despite attempting the suggested Solution, it didn't resolve the problem within my code. Below is ...

When attempting to receive a response from a web service via web socket, the 'Any' type does not support subscript members

I have attempted to use Dictionary instead of Any, but I am unable to retrieve the desired value. My goal is to only display the "msg" value from the text in the code snippet below: webSocket.event.message = { message in if let text = mess ...

Communicating from JQuery-UI to Angular 6 using callbacks

I incorporated the jQuery-UI MonthPicker into my Angular 6 application, and now I am looking to trigger an Angular action whenever the date changes: ngOnInit() { $(document).ready(function() { $('#myMonthPicker').MonthPicker( ...

The onChange function in React is not behaving as I anticipated

Consider the following data structure for tables: an array of objects containing nested objects: [ { "1": { "1": "Item s ", "2": "Manufacturer ", "3" ...

I am encountering a problem with my Material UI react-swipeable-views while using TypeScript

It seems that there is a mismatch in the version of some components. import * as React from "react"; import { useTheme } from "@mui/material/styles"; import Box from "@mui/material/Box"; import MobileStepper from "@mui/ma ...

Any idea how to dynamically insert rows and columns into a table or div element?

Can anyone assist me with this task? I have successfully completed the visual process I intended to do. How can I achieve this structure using AngularJS? The data will be stored in Json format. When the "+" symbol is clicked in a certain direction, the fi ...

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...

Making various API calls using Python's JSON module

Struggling to handle multiple requests to an API, consolidate responses, and convert the data into a dataframe. The issue lies in creating the dataframe with JSON files as it results in an empty dataframe despite gathering necessary data. Removing 'df ...

Developing applications using the combination of Vue.js, JSX, and

While I have no issues using TypeScript with single file components (.vue files), I encountered problems when attempting to use it with JSX files. Two errors arise, one in my index.ts file. I'm uncertain if there was a mistake made in my configuration ...

I am encountering 404 errors when attempting to load Angular2 files using Express - what could be causing this issue?

Having experience with using Express, I am attempting to apply the guidelines provided here to the express template. After generating the latest Express project, I included the following in my package.json file. "dependencies": { "angular ...

Unattended checkbox leads to AJAX feedback stalling with a spinning loading icon

Hello there! I have been working on a form that includes a checkbox, a textarea, and some input fields. I've managed to successfully submit all the form data to my localhost using POST to the database. However, I've encountered an issue when the ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

Building Angular CLI Applications with Separate SCSS Files for Browser Loading

Below is how I am importing the scss file: import { Component, OnInit, ViewEncapsulation } from '@angular/core'; @Component({ ...., styleUrls: ['../../scss/dashboard_admin.scss'], encapsulation: ViewEncapsulation.None }) e ...

How can you determine the number of times a particular digit appears around a specific position in a TypeScript array

(Utilizing Typescript for assistance) I am looking to determine the number of occurrences of the digit 2 surrounding a specific position within an array. The function takes in the position coordinates as parameters - param 1 for row and param 2 for column. ...

Exploring NestJs: The Importance of DTOs and Entities

In my project, I'm currently experimenting with utilizing DTOs and Entities in a clever manner. However, I find it more challenging than expected as I develop a backend system for inventory management using NestJs and TypeOrm. When my client sends me ...

The compatibility between json_encode and JSON.parse is not seamless

I am encountering a situation on my PHP page where I am using json_encode and getting the following output: {"id":"761","user":"Moderator","message":"test"} {"id":"760","user":"Patrick","message":"test"} My goal is to parse these values using JSON.parse ...