Why are my values not being applied to the model class in Angular 7?

I'm currently developing an online shopping website where I have defined my order Model class as shown below:

import { User } from './user.model';

export class Order {
  constructor(){}
  amount: Number = 0;
  status: String = "";
  date: String = '';
  products: [any];
  userId: String = '';
  user : User;
}

My user model looks like this:

export class User{
  name: string = '';
  email: string = '';
  country: string = '';
  city: string = '';
  mobileNumber: string = '';
  address: string = '';
  postalCode : string = '';
  nearBy : string = '';
  _id : string = '';
}

In my cart service file, I am calculating the total amount of the order using the following code snippet:

// Total amount
public getTotalAmount(): Observable<number> {
    return this.cartItems.pipe(map((product: CartItem[]) => {
    return products.reduce((prev, curr: CartItem) => {
    return prev + curr.product.price * curr.quantity;
    }, 0);
 }));
}

Now, in my checkout component file, I am assigning values to the order Model class like this:

isUserLoggedIn: boolean = false;
orderRawData: any;
order: Order;

placeOrder() {
this.cartService.getTotalAmount().subscribe(total=>{
  if (total) {
    console.log('amount : ',total);
    this.order.amount = total;
    this.orderRawData = JSON.parse(localStorage.getItem('cartItem'));
    if (this.isUserLoggedIn) {
      this.order.userId = this.user._id;
    }else{
      this.order.user = this.user;
    }
    this.orderRawData.forEach((item,index)=>{
      this.order.products.push({
        id : item.product._id,
        quantity : item.quantity
      })
    })
    this.order.date = new Date().toLocaleString();
    this.order.status = 'Pending';
    console.log(this.order);
   }
 })

}

However, when I try to run the code, I encounter the following error message:

https://i.sstatic.net/Pkiff.png

Can anyone point out what mistake I might be making here?

Answer №1

The variable order has been declared but remains uninitialized:

order: Order;

As a result, it is undefined when attempting to modify its properties.

this.order.amount = total;
//        <--- undefined here

You must first assign a value to order, such as:

this.orderService.getOrder().subscribe(order => {
  this.order = order;
});

Only then can you proceed with updating its properties.

Answer №2

Your order seems to be in the 'Order' format, but it has not been initialized properly.

You can resolve this by either:

1) Defining the order like so:

order: Order = {
       amount: 0,
       status: null,
       ....
   }

or 2) Updating the Order class as follows:

export class Order {
    amount: Number;
    status: String;
    ...

    constructor(_amount: Number = 0, _status: String = '', ...) {
        this.amount = _amount;  
        this.status = _status;
        ....
    }
}

In your component:

order: Order = new Order();

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

Adding elements to a JSON array in JavaScript/AngularJS

Looking for help with inserting a new item "uid" into a JSON array. Here is the initial array: var testArr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}] The desired output after inserting the "uid" would be: var testArr=[{name:"nam ...

Troubleshooting Problem with Angular JS Page Loading on Internet Explorer 9

My angularjs single page application is encountering issues specifically in IE9, despite functioning perfectly in Chrome and Firefox. The initial load involves downloading a substantial amount of data and managing numerous dependencies through requireJS. ...

Pressing the button updates the value in the input field, but the input field continues to

I need some assistance with my e-commerce platform. I am trying to implement a button that adds items to the shopping cart, but I'm encountering an issue where the value in nbrSeats (my list of values) changes in the data, yet the input field displays ...

What is the best way to create a command that updates the status in Discord using discord.js?

I'm currently working on a command for my Discord bot using discord.js. The purpose of this command is to change the bot's status whenever an admin of the server triggers it. I've attempted to create the command, but unfortunately, it's ...

Obtaining the calculated background style on Firefox

Back when my userscript was only functional on Chrome, I had a setup where I could copy the entire background (which could be anything from an image to a color) from one element to another. This is how it looked: $(target).css('background', $(so ...

Employing monaco-editor alongside typescript without webpack within an electron endeavor

I need help incorporating the monaco-editor into my electron project built with TypeScript. Using npm install -D monaco-editor, I installed it successfully and imported it with import { editor } from "monaco-editor";. Despite not receiving any mo ...

Create random animations with the click of a button using Vue.js

I have three different lottie player json animation files - congratulations1.json, congratulations2.json and congratulations3.json. Each animation file is configured as follows: congratulations1: <lottie-player v-if="showPlayer1" ...

Instructions on changing the color and font weight of an asterisk within a Textfield using Material UI

Is there a way to style the asterisk in red and bold within a Textfield using material UI? I have a placeholder text without a label, as my label is null or empty. I would like to make the placeholder star RED. Is this possible? Here is the code snippet: h ...

This function is designed to only work under specific conditions

Looking for assistance with a function that takes an item ID as input and changes its border when pressed. The goal is to increase the border width by 2px when there is no border, and remove the border completely when pressed again. Currently, only the f ...

Removing validators in Angular forms after submitting the form and resetting it

I am currently working on an Angular app that includes a form. Whenever I click the submit button, the reset() function gets triggered on the form. However, after the reset() function is called, all inputs are marked as having errors. I have tried using fu ...

No location matched any routes

I'm currently working on a notes application, and I've encountered an error when trying to edit the notes. The error message says "No routes matched location id ...". Any idea what could be causing this issue? The approach I'm taking is to ...

Count the number of URL segments using JavaScript and jQuery

Can anyone suggest an efficient method to count the number of segments in a URL using JavaScript/jQuery? For instance: www.myexampleurl.com/section1/section2/section3 should output 3 ...

Steps to resolve the issue: angular/[email protected] - unable to resolve the dependency

Encountering a challenging compiler error, I am determined to find a solution. Despite numerous attempts to install different library versions, the issue persists. It appears that the firebaseui-angular package necessitates an alternative angular/fire ver ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...

How to effectively pass custom props or data to the Link component in Next JS

As I dive into Next JS, I've hit my first roadblock. Currently, I am working on a page that showcases various podcast episodes with preview cards on the homepage. The card component code looks like this: import React from 'react'; import Li ...

When requesting a Node.js API from Javascript fetch, the session custom property is throwing an undefined error

I am currently working on a User Login Project, where the APIs are built using Node.js and Express. The UI part is developed using HTML and JavaScript, with these components existing as separate projects. Upon user login, a fetch call is made in JavaScrip ...

Node.js: Leveraging Express to Compare URL Parameters and Handle Delete Requests with Array Values

Having some issues with the Express routes I set up for an array of objects and CRUD operations. Everything works smoothly except for the "Delete" operation. I am trying to delete an object by matching its URL parameter ID with the value of its key. Howev ...

How can I dynamically modify the class name of a specific element generated during an iteration in React when another element is clicked?

My goal is to dynamically add a class to a specific element within a table row when a user clicks a remove button. The desired behavior is to disable the entire row by adding a "removed" class to the containing row div. The challenge is that there are mult ...

Exploring an Angular Real-World Example Application on Github - Resolving the Following Bug

my surroundings. export const environment = { production: false, api_url: 'localhost:3306/api' }; my personal server is at localhost:3306 (MAMP) The instructions provided are to edit src/environments/environment.ts in order to ch ...

Is there a user-friendly interface in Typescript for basic dictionaries?

I'm not inquiring about the implementation of a dictionary in Typescript; rather, I'm curious: "Does Typescript provide predefined interfaces for common dictionary scenarios?" For instance: In my project, I require a dictionary with elements of ...