Utilize nested object models as parameters in TypeScript requests

Trying to pass request parameters using model structure in typescript. It works fine for non-nested objects, but encountering issues with nested arrays as shown below:

export class exampleModel{

    products: [
        {
            name: string,
            address:string,
            product_sizes: [
                {
                    quntity: number,
                    price: number,
                    id: [
                        number
                    ]
                }
            ]
        }
    ]

} 

After creating the model, initializing it as follows:

  productRequestObject : exampleModel = <exampleModel>{}

Attempts to assign values result in an error:

    this.productRequestObject.products[0].name = sessionStorage.getItem('name')

Error message received:

Cannot read property '0' of undefined

Any suggestions or insights on what might be missing are greatly appreciated!

Answer №1

Start off by creating a blank object without any fields, such as projects. To properly handle this, it's best to first define interfaces and models. Then proceed to instantiate and piece them together like a puzzle based on their hierarchical structure.

Define the necessary interfaces in interfaces.ts

export interface IProductSize {
    quantity: number;
    price: number;
    id: Array<number>;
}

export interface IProduct {
    name: string;
    address:string;
    product_sizes: Array<IProductSize>;
}

export interface IRequest {
    products: Array<IProduct>;
}

export interface IExampleModel {
    requests: Array<IRequest>;
}

To complement this, define your classes in models.ts

export class ProductSize implements IProductSize {
    constructor(
        public quantity: number,
        public price: number,
        public id: Array<number>){}
}

export class Product implements IProduct {
    constructor(
        public name: string,
        public address:string,
        public product_sizes: Array<IProductSize>){}
}

export class Request implements IRequest {
    constructor(public products: Array<IProduct>){}
}

export class ExampleModel implements IExampleModel {
    constructor(public requests: Array<IRequest>){}
}

You can now proceed to construct your object.

let productSize: IProductSize = new ProductSize(0, 0, []);
let product: IProduct = new Product('', '', [productSize]);
let request: IRequest = new Request([product]);
let productRequestObject: IExampleModel = new ExampleModel([request]);

Finally, access the desired field

 this.productRequestObject.products[0].name = sessionStorage.getItem('name');

This method offers flexibility and complete control over each layer of your nested structure when working with Angular.

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

Troubleshooting: Angular 6 issue - Unable to toggle visibility using ngIf

I am currently learning Angular and I'm working on the app.component.html as shown below: <app-login *ngIf="!loggedIn"></app-login> <section *ngIf="loggedIn" style="background:#EBF0F5;"> <div class="container"> ...

Service Injected into ng-template outlet context not defined

I'm encountering an issue where I am trying to pass a function that references an injected service to a button within the context of an outlet, but for some reason, the injected service is coming up as undefined. Here is the code snippet in question: ...

Effectively enhance constructor by incorporating decorators

Is it possible to properly extend a class constructor with decorators while maintaining the original class name and static attributes and methods? Upon reading the handbook, there is a note that cautions about this scenario: https://www.typescriptlang.or ...

Incompatibility Issues with TypeScript Function Overloading

In the process of setting up an NgRx store, I came across a pattern that I found myself using frequently: concatMap(action => of(action).pipe( withLatestFrom(this.store.pipe(select(fromBooks.getCollectionBookIds))) )), (found at the bottom ...

Can *ngFor in Angular handle asynchronous rendering?

Within the code snippet provided, the line this.images = response.map( r => r.url).slice(0,10); populates the images array. The data is then rendered in the view using ngFor. Following this, a jQuery function is invoked to initialize an image slider. Ho ...

Troubles with implementing child routes in Angular 6

I'm having trouble getting the routing and child routing to work in my simple navigation for an angular 6 app. I've configured everything correctly, but it just doesn't seem to be working. Here is the structure of my app: └───src ...

Enhancing the Look of Typeahead in ng-bootstrap

I'm finding it difficult to customize the appearance of the dropdown menu in ng bootstrap typeahead. The input styling works fine (the component only includes an input/typeahead), but I am unable to style the dropdown. I've tried using both the ...

Ensuring Angular2 Javascript is validating only numerical input and not accepting characters

Access the full project here (excluding nodes_modules): Note: After running the project, all actions related to this issue can be found in the "Edit All" section of the website. Click on that to view the table. The main objective of this website section ...

Launching npm start does not automatically open a browser tab

I'm currently learning angularjs 2 and I'm eager to create my first application using the framework. Following the guidelines on their official website, I proceeded with all the steps outlined in this link. In step 6, I am required to run the com ...

What is the best way to find out if multiples of a specific time interval can evenly divide the time between two

I'm currently utilizing Luxon for handling dates and durations. I have two specific dates and an ISO duration, and I am looking to figure out how to determine if the interval between the dates is a multiple of the specified duration without any remain ...

Dealing with a nested object problem in Angular using TypeScript

I am currently working on an Angular 15 application that is designed to showcase information about different games to users. Within the application, I have a global object structured like this: GAMES_INFO: { skyroads: { name: 'Sky Roads&a ...

Creating a custom login directive in Angular 2 and utilizing location.createComponent for dynamic

Incorporating a login system into my Angular app has been a priority for me lately. I came across a helpful resource here that outlines the process. However, I encountered an issue with the custom RouterOutlet directive as shown below: import { ElementRef ...

Issue: ng test encountered a StaticInjectorError related to FormBuilder

I recently started using ng test to run tests on my Angular application. I utilized the Angular-Cli tool to create modules and components, and the .spec.ts files were generated automatically. During one of the tests, I encountered the following error: ...

The installation of Angular CLI through npm has unfortunately encountered an error

After following the steps from this post to remove the old installation, I encountered an issue during the last step: [sudo] npm uninstall -g @angular/cli [sudo] npm cache verify [sudo] npm install -g @angular/cli During the final step, I faced difficult ...

What is the best way to extract a property if it may be undefined?

Can anyone help with this TypeScript error I'm encountering during build time? Any suggestions would be appreciated. Error Message: TypeError: Cannot destructure property 'site' of '(intermediate value)' as it is undefined. export ...

Collection of personalized forms where the parent is a FormGroup

One scenario I'm working on involves creating multiple custom formgroup classes that have FormGroup as their parent class, structured like this: export class CustomFormGroup1 extends FormGroup { //custom properties for this FormGroup const ...

I possess information stored within the array object below, and I aim to transform it into a different array object format

Here is the response I received from my API: let data = [ { date: '2021-04-27', formatted_date: 'Apr 27', location: [ { date: '2021-04-27', formatted_date: 'Apr 27', countr ...

Preventing the "Block-scoped variable used before its declaration" error in an Angular/TypeScript tree structure with child/parent references

Imagine a scenario where we have a set of simple nodes/objects forming a tree structure, each with parent and children references. The challenge lies in the need to reference both the parent and children nodes independently from the tree itself. This means ...

Issue downloading file in Angular using Filesaver.js is causing problems

I am utilizing Filesaver.js to attempt downloading files from my Express (NodeJS) backend. Below is the backend code responsible for file downloads. It incorporates a middleware to authenticate the request. res.download(url, function (err) { if (err) ...

What are the benefits of reverting back to an Angular 1 directive instead of using an Angular 2 application

Our team has created numerous Angular 1 components and is eager to incorporate them into our Angular 2 application. However, the documentation suggests that we must downgrade the Angular 2 application in order to integrate and utilize the Angular 1 direc ...