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:

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

The React component fails to re-render upon the initial state update

Currently, I am working on a straightforward survey that requires simple Yes or No answers. The questions are stored in a separate file called QuestionsList.js: Here is the list of questions: const QuestionsList = [ "Do you believe in ghosts?", "Have you ...

Implement a jQuery loop that utilizes the fadeIn effect

Currently, I have a basic jQuery function in place to generate a small image slider: function gridhover() { $(".grid-item .slide-image").each(function(index) { $(this).delay(400*index).fadeIn(300); }); } $( ".grid-item" ).hover(function() ...

Monitor the DOM for visibility changes in Selenium WebDriver and PjantomJS before proceeding

I am currently creating automated test scripts using selenium-webdriver, phantomJS, and mocha. The script file I'm working with is a JavaScript file. My goal is to wait until an element (<a>) is fully visible before clicking on it. Let me pro ...

Running a code from a plugin in Wordpress site

I am currently utilizing the "wp-video-lightbox" plugin for WordPress, which generates small floating boxes for my videos. I am interested in incorporating variables like http://www.example.com/?video3 to provide shortcuts similar to what YouTube offers. ...

What is the reason for a boolean extracted from a union type showing that it is not equivalent to true?

I'm facing a general understanding issue with this problem. While it seems to stem from material-ui, I suspect it's actually more of a typescript issue in general. Despite my attempts, I couldn't replicate the problem with my own types, so I ...

To change the font color to red when clicked, I must create a button using HTML, CSS, and Javascript

Currently, I am utilizing CodePen to assess my skills in creating a website. Specifically, I am focusing on the HTML component. My goal is to change the font color to blue for the phrase "Today is a beautiful sunny day!" Here is the snippet of code that I ...

Focus on a primary window

When a new window is opened using the target attribute of _blank, is it possible to target links to open in the original "parent" window? Appreciate your help! ...

The element is inherently an 'any' type as the expression of type 'number' does not have the capability to index type 'Object'

Hey there, I'm currently in the process of learning Angular and following along with the Note Mates tutorial on YouTube. However, I've hit a stumbling block as I attempt to implement sorting by relevancy. The issue lies with the code snippet belo ...

Unable to modify the value of a key within an object using TypeScript

I'm struggling to update the value of a key within an object using TypeScript. Here's an overview of the types I'm working with: export enum BAR_TYPES { apple = "apple", banana = "banana" } export type BarTypes = ...

Creating an array object in TypeScript is a straightforward process

Working on an Angular 4 project, I am attempting to declare an attribute in a component class that is an object containing multiple arrays, structured like this: history: { Movies: Array<Media>, Images: Array<Media>, Music: Array<Medi ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

Reloading the current route in Angular 4 using routerLink

Is it possible to refresh the current page by clicking on a link using routerLink? An example of the menu structure I have is: <ul> <li><a routerLink="home">Home</a></li> <li><a routerLink="users">Users</a& ...

Only consider valid values for input and ignore any zeros

I am working on a form where I need to accept any number, regardless of if it's negative, a float, or a long integer. I have implemented code to not allow null, undefined, or empty values, but I encountered an issue where entering 0 is being read as e ...

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...

Utilizing the <slot> feature in Angular 5 for increased functionality

Currently, I am working on a single page application (SPA) where Vue framework has been utilized for development purposes. Front-End: Vue Back-End: NodeJs Within my application, there are other sub-modules built in Angular 4. I am looking to replicate th ...

Refresh the array using Composition API

Currently, I am working on a project that utilizes Vue along with Pinia store. export default { setup() { let rows: Row[] = store.history.rows; } } Everything is functioning properly at the moment, but there is a specific scenario where I need to ...

Having trouble installing sqlite3? Encounter an issue like this: "srcdatabase.cc(35): error C2248: 'Napi::Env::DefaultFini': cannot access private member declared in class 'Napi::Env'"?

Encountering issues while trying to install sqlite3 for a Strapi app I've attempted using yarn to install sqlite3 in various ways, but to no avail. Below is the error log: Error message: Issue with installing sqlite3 when creating a Strapi app (..& ...

Having issue updating a MySQL table using an array of objects in JavaScript

Working on a personal project involving React.js for the front-end, Node.js/express for the back-end, and mySQL for the database. The current array is as follows: horaires = [ { jour: 'Lundi', horaire: 'Fermé' }, { jour: 'Mar ...

rxjs - monitoring several observables and triggering a response upon any alteration

Is there a way to watch multiple observables and execute a function whenever any of them change? I am looking for a solution similar to the functionality of zip, but without requiring every observable to update its value. Also, forkJoin isn't suitable ...