Angular: Issue with object instantiation - Unable to assign property

Having trouble populating my array due to instantiation issues.

Defined Models:

user: User = {
  firstName: "",
  lastName: "",
  address: ""
}
order: Order = {
  OrderId: "",
  User: this.user,
  TotalPrice: 0,
  OrderItems: []

}

Attempting to populate the Order:

    this.Identity.getMail().then(user => this.order.OrderId == user.email);
this.order.User = this.user;
this.order.TotalPrice = this.cartTotal;
this.cartItems.forEach((item, index) => {
  this.order.OrderItems[index].ProductName = item.productName,
  this.order.OrderItems[index].ProductPrice = item.price,
  this.order.OrderItems[index].ProductQuantity = item.quantity
})

Encountering an error:

CartFullComponent.html:21 ERROR TypeError: Cannot set property 'ProductName' of undefined

How can I properly instantiate order.OrderItems to accept values?

Answer №1

To simplify the process, consider using this.order.OrderItems.push(item) instead of manually setting properties.

this.Authentication.getUserInfo().then(user => this.order.OrderId === user.email);
this.order.Customer = this.customer;
this.order.TotalCost = this.cartTotal;
this.itemsInCart.forEach((item, index) => {
  this.order.OrderItems.push({ 
    Name : item.itemName, 
    Price : item.cost,
    Quantity : item.amount
  });
})

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

Request with missing authentication header in Swagger OpenAPI 3.0

When generating the swagger.json using tsoa for TypeScript, I encountered an issue. Even after adding an access token to the authorize menu in Swagger and making a request to one of my endpoints, the x-access-token header is missing from the request. What ...

Error: Typings: Invalid syntax - Unexpected symbol =>

Every time I run a typings command, I encounter the following error: AppData\Roaming\npm\node_modules\typings\node_modules\strip-bom\index.js:2 module.exports = x => { ^^ SyntaxError: Unexpected tok ...

Error in Angular 4: Expression Updated After Being Checked

Encountering the ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'. error when validating the reactive form for validity. createForm public creat ...

What is the process for updating button text upon clicking in Angular?

To toggle the text based on whether this.isDisabled is set to false or true, you can implement a function that changes it when the button is clicked. I attempted to use this.btn.value, but encountered an error. import { Component } from '@angular/core ...

Tips for determining the minimum value within an array of objects across multiple keys using a single function

I am currently tasked with the challenge of determining the minimum value from an array of objects that contain multiple keys. My ultimate goal is to identify the minimum value among all keys or specific keys within the objects. For instance var users = ...

Angular and ngrx are experiencing an issue involving an infinite loop within a selector

Is it possible to dispatch an action within a selector in a single store? this.store$.pipe(select(selectPersonByName, {personSelectorProps: this.id[]0})) .subscribe(history => { this.store$.dispatch(selectAssignWorkHisto ...

Angular CLI "serve" encountered a 404 status code when using CURL, yet the webpage is loading successfully in the browser

As I develop a new application using angular2 within Electron, I always aim to automate every aspect of the process. To achieve this, I have implemented various NPM scripts for serving, building, and packaging within the Electron wrapper. However, I am cur ...

Is there a way to reverse the direction of the slider's track?

Our goal in the design is for users to select a value between 0 and 20, with the selected range being that value up to 20. Currently, Angular Material slider component highlights values from 0 up to the selected value as the active track. Is there a way to ...

`Database Schema Enforcement in Firestore: Custom Objects vs Security Rules`

Firestore, being a noSQL database, is schemaless. However, I want to ensure that the correct data type is being passed in. Custom Objects As per Firebase documentation, https://firebase.google.com/docs/firestore/manage-data/add-data class City { const ...

What is the process for subscribing to the output of a flatMap operation?

Is there a way to subscribe to the result of flatMap in this code block? timer(0, 2000) .pipe( flatMap(() => this.scannerService.scan(this.scanType)), takeWhile(res => res.errorDesc !== "SUCCESS") ) .subscrib ...

Can I utilize a specific interface type within another interface?

Can I pass an object along with its interface to a React component? Here's a sample of the interface I'd like to incorporate: interface TableProps { ObjectProps: Interface (not functioning properly); objects: Array<ObjectProps>; } Is i ...

Splitting files with Webpack generates dynamic chunk files

Anticipating to only have two distinct chunks named vendors and commons, webpack unexpectedly generates a new chunk file for specific entries with a delimiter. optimization: { splitChunks: { chunks: 'all', cacheGroups: { ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

Cloud Formation from CDK doesn't pause for addDependency to finish

I'm currently in the process of building a CDK stack and I am fairly new to CDK. My goal is to create a Simple Email Service (SES) ConfigurationSet followed by an EmailIdentity. The issue I encountered is that the creation of the EmailIdentity fails d ...

What could be the reason for the component not receiving data from the service?

After attempting to send data from one component to another using a service, I followed the guidance provided in this answer. Unfortunately, the data is not being received by the receiver component. I also explored the solution suggested in this question. ...

Encountered a higher number of hooks rendered compared to the previous render error on a component without any conditional hook usage

Within my codebase, I have a component that is responsible for rendering a clickable link to initiate a file upload process. import { gql, useLazyQuery, useMutation } from '@apollo/client'; import { useEffect, useState } from 'react'; i ...

Navigating through a list using tabs and automatic scrolling to a specific index in React with Material UI's Scrollspy

If there was a vast array of items, each belonging to a specific category, const categories: string[] = [0, 1, 2, 3, 4, 5]; const items: {name: string, category: number}[] = [{name: "foo", category: 1}, {name: "bar", category: 1}, {name ...

A guide on automatically focusing on a Material UI Formik form TextField using React and TypeScript

I'm attempting to automatically focus my textField, but the 'autoFocus' attribute only seems to work after I submit the form and add a value. If no values are added (i.e. when opening the miui modal for the first time), the autoFocus does no ...

Ensure a field is required if the integer field is not empty in Angular Schema Form

I am currently working on setting up a form using Angular JSON Schema Form. My goal is to make one field (dropdown1) required only when another field (number1) has been filled in. I have managed to successfully get the following form + schema to function p ...

Implementing basic authentication and Cross-Origin Resource Sharing (CORS) in

I am currently attempting to make a simple HTTP API call using Angular to a standard API with Basic HTTP Authentication. However, I am encountering an issue where the browser is blocking the request with a "Cross-Origin Request Blocked" error message, citi ...