What is the proper way to create a child JSON object in Angular using TypeScript?

I have a model.ts file.

export class MainClass {
    someVar: string;
    var2: string;
    subClass: SubClass;
    contact: ContactList;
}

export class SubClass {
  subItem: {
    item1: string;
    item2: string;
    item3: string;
  }
  constructor() {}
}


export class ContactList {
  itemList: ListItems[];
  constructor() {}
}


export class ListItems {
  list1: string;
  list2: string;
  list3: string;  
}

In my coding journey, I encountered a service.ts file where critical setter methods reside to update the model.

constructor(private model: SomeModel) {}

//some code

updateList(param1, param2, param3) {
    this.model.subClass.subItem.item1 = param1;//doesn't work
    this.model.contact.item[0].list1 = param2;//doesn't work
    this.model.someVar = param3;//works
}

While trying to enhance the functionality, I faced the obstacle of "Can't read property subItem of undefined" error message when attempting to update subClass and contact. It's clear that initializing the subItem and itemList within the model's constructor is necessary, but grasping the correct syntax seems to be challenging. How can I effectively initialize and modify the model structure?

Answer №1

In order to properly set up the constructor within the model, I followed this structure:

export class MainClass {
  someVar: string;
  var2: string;
  subClass: SubClass;
  contact: ContactList;
  constructor() {
    this.subClass = new SubClass();
    this.contact = new ContactList();
  }
}

export class SubClass {
  subItemVar: SubItem;
  constructor() {
    this.subItemVar = new SubItem();
  }
}

export class SubItem {
  item1: string;
  item2: string;
  item3: string;
}

export class ContactList {
  itemList: ListItems[];
  constructor() {
    this.itemList = new Array<ListItems>();
  }
}

export class ListItems {
  list1: string;
  list2: string;
  list3: string;
}

Answer №2

The reason why subClass and subItem are showing as undefined is because they have not been initialized yet. To resolve this, you need to create a new instance for them before assigning values:

Update SomeModel to MainClass or utilize the .map function for mapping purposes.

this.model.subClass = new SubClass();
this.model.subClass.subItem =  {item1:'123', item2: '222', item3: '333'};

Answer №3

Make sure to call the constructor of any complex types you want to initialize in your MainClass.

export class MainClass {
    someVar: string;
    var2: string;
    subClass: SubClass();
    contact: ContactList();
}

Pay attention to the parenthesis. If you have more complicated initialization steps, there may be other considerations to take into account. For example, in your SubClass, ensure that subItem has a constructor if you want it to be initialized when you create an instance of SubClass.

An alternative approach for initializing subItem in your parent class would be to include something like this in the constructor:

constructor() {
        //... some init code
        this.subItem = new Array<SubItemModel>();
        this.subItem.push(new SubItemModel());
    }

I hope this explanation is helpful,

Answer №4

The reason behind encountering this error is that the variables subClass, subItem, and contact have not been properly defined. In order to resolve this issue, it is recommended to make adjustments to the models as indicated below:

export class MainClass {
    someVar: string;
    var2: string;
    subClass: SubClass;
    contact: ContactList;
    constructor() {
      if(!this.subClass)
      this.subClass =new SubClass();
      if(!this.contact)
      this.contact =new ContactList();
    }
}

export class SubClass {
  subItem: SubItem;
  constructor() {
    if(!this.subItem)
     this.subItem =new SubItem();
  }
}
export class SubItem {

    item1: string;
    item2: string;
    item3: string;

  constructor() {}
}


export class ContactList {
  itemList: ListItems[]=[];
  constructor() {}
}
export class ListItems {
  list1: string;
  list2: string;
  list3: string;  
}

Implementation in service:

constructor(private model: SomeModel) {}

//Some code

updateList(param1, param2, param3) {
    this.model.subClass.subItem.item1 = param1;

 this.model.contact.itemList = [];
 let listItem: ListItems =new ListItems();
 listItem.list1 =param2
 this.model.contact.itemList.push(listItem)
    this.model.someVar = param3;
}

This guidance aims to assist you in recognizing the errors made and adapting the code according to your needs. We hope this information proves useful.

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

Obtaining a subset of data from firebase

I am currently working on retrieving a sub-collection from the Firestore database using Angular. In my database, I have a collection called 'Company' which contains fields for 'Name' and 'Id', as well as a sub-collection named ...

An undefined variable in Angular 2's evaluation

I am currently working with the following code: @ViewChild('MondayPicker') MondayPicker; @ViewChild('TuesdayPicker') TuesdayPicker; @ViewChild('WednesdayPicker') WednesdayPicker; @ViewChild('ThursdayPicker') Thursda ...

The type 'string' cannot be assigned to the type '"GET" | "get" | ...'

In my custom hook, I utilize the axios library for making requests: const useCustomHook = ({ endPoint = "", method = "GET", options = {} }) => { const [data, setData] = useState([]); const [request, setRequest] = useState<AxiosRequestConfig> ...

Cross-Origin Resource Sharing (CORS) Issue: HTTP status is not okay. GoLang Mux API

When trying to perform HTTP requests using an Angular 17 App, I keep encountering the following response from the browser: Access to XMLHttpRequest at 'http://localhost:8082/login' from origin 'http://localhost:4200' has been blocked ...

Combining and compressing files in an Angular 2 quick start project

What is the best way to bundle and minify an Angular 2 quick start project to decrease HTTP requests during the initial load? When the first page of the Quick start project loads, it generates approximately 300 HTTP requests, resulting in significant dela ...

Issue in VueJs where mutations do not properly save new objects to the state

I am facing an issue with updating my vuex store after modifying my user credentials in a component. Below is the code snippet for reference: mutations: { updateUserState: function(state, user) { state.user = user; }, } actions: { updat ...

Extracting data from an array using Angular

Currently, I am developing an Angular application that involves handling an array structured like the one below. [ { Code: "123", Details:[ { Id: "1", Name: "Gary" }, { ...

I am curious as to why the Angular route resolver seems to only pay attention to the initial value of my observable

Currently, I am exploring Angular 15 and experimenting with the routing resolver handler to pre-fetch products before loading a product-list component. The main aim is to display the products in the product-list component. As a newcomer to stackoverflow, I ...

Handling network connection errors in Ionic 2

Handling API calls in my provider involves the following method: listSavedJobs() : Promise <any> { let headers = new Headers({ 'Authorization': localStorage.getItem('token') }); return this.http.get(this.savedJobs, { h ...

Updating an array nested within an item of my state array using Angular 2 ngrx

Within my reducer function, I am looking to include an element that is nested within an array, following this JSON structure received via http services: JSON structure: { "id": "09fabf9a-e532-4d2a-87cc-bd949a0a437f", "title" ...

The autoimport feature is not supported by the Types Library

My latest project involves a unique library with only one export, an interface named IBasic. After publishing this library on npm and installing it in another project, I encountered an issue. When attempting to import IBasic using the auto-import feature ( ...

Angular Error: The call stack has surpassed the maximum size limit

Having a lengthy HTML file can be overwhelming, so breaking it down into components is a great solution. However, I recently encountered an issue in my app.component.html where adding more than 2 selectors caused an error to occur. NodeInvocationException ...

Spying on ActivatedRoute.queryParams is not possible in Angular when using Jasmine

Is there a way to effectively spy on a stubbed Angular Service method that should return an Observable like ActivatedRoute.queryParams? The below code snippet shows my failing test case: import { TestBed, ComponentFixture } from "@angular/core/testing"; i ...

How to optimize the loading speed of background images in an Angular application

Utilizing Angular v6, typescript, and SASS for my project. A CSS background image is set for the homepage, however, it's a large photo that always takes too long to load. Custom CSS: @import '../../../scss/variables'; :host { .wrapper { ...

How to activate the close function of ionic-datepicker when tapping the hardware back button in Ionic 4

Utilizing ionic-datepicker in my app (ionic v-4), here is the corresponding template: <ion-datetime formControlName="meeting_date" display-format="MMM DD, YYYY"></ion-datetime> The datepicker (i.e ion-datetime) closes upon clicking cancel/do ...

Setting up SonarQube for an AngularJS project utilizing Typescript is a breeze with these simple steps!

After setting up SonarQube and SonarScanner and successfully scanning my project, I noticed that all metrics appear on my screen except for code coverage, which remains at 0%. What could be causing this issue? #----- Default SonarQube server sonar.host.url ...

The Cypress tests run successfully on a local machine, but encounter issues when running on Gitlab CI

My current setup involves utilizing Cypress to test my Angular application. Interestingly, everything runs smoothly when I execute the tests locally. However, the scenario changes once I run the tests in Gitlab CI as it ends up failing. Looking at my pack ...

Tips for avoiding the <p> and <br> elements while using a ContentEditable div

Upon pressing the enter key, the editor automatically inserts paragraph and page break elements. What are some strategies to avoid these unwanted elements in the editor? https://i.sstatic.net/r4jU1.png ...

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

Typescript on the client-side: what is the best way to eliminate circular dependencies when using the factory method design pattern?

In my code, I have implemented the factory method pattern. However, some instances using this pattern end up with circular dependencies. Removing these dependencies has proven to be a challenge for me. To illustrate, consider the following example: // fact ...