What is the correct way to start a typed Object in TypeScript/Angular?

As I delve into the world of Angular and TypeScript, I am faced with a dilemma regarding how to initialize an object before receiving data from an API request.

Take for instance my model:

//order.model.ts
export class Order {
  constructor(public id: number, currency: string, public contact: Object, public items: Array<Object>) {}
}

In one of my components, let's say the App component, I attempt to instantiate this model:

//app.component.ts
export class AppComponent {
  @Input()
  public order: Order = new Order();
}

However, when trying to create a new Order object, it requires 4 arguments but none were provided. Should I pass in undefined or empty values for each attribute of Order?

In React (without TypeScript), I would simply initialize with an empty object:

this.state = {
 order: {}
}

What is considered best practice for handling this situation in Angular and TypeScript?

Answer №1

A practical approach would involve passing 4 default arguments to the constructor if using the current setup.

For instance, initializing a public order like this: Order = new Order(1, '', {}, []);

Alternatively, you can make each property nullable by adding a ? like this:

export class Order {
  constructor(public id?: number, currency?: string, public contact?: Object, public items?: Array<Object>) {}
}

If the class is solely for type checking without any functionality, it's recommended to declare an interface as shown below (nullable properties denoted by ?s):

export interface Order {
    id: number;
    currency: string;
    contact: Object;
    items: Object[];
}

In your component, avoid initializing the value until all necessary values are available:

//app.component.ts
export class AppComponent {
  @Input()
  public order: Order;

  // Example method for setting values
  setValues(id: number, currency: string, contact: Object, items: Object[]) {
    this.order = {
      id: id,
      currency: currency,
      contact: contact,
      items: items
    }
  }

  // Example method for fetching data from backend
  getData() {
    this.service.getData().subscribe(result => {
       this.order = result;
    });
  }
}

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

Utilizing Ajax to upload various files from separate input sources simultaneously

I want to upload multiple textual/select inputs along with two different file inputs to a PHP file using Ajax. The images from the file inputs are specific and need to be identified by their input names, so I cannot use <input type="file" multiple>. ...

What is the correct method for storing a response in an array variable in Angular?

I am looking to save the response data from an API call in a variable and display it in the component.html file. Component.ts file : public coinsHistory = []; this.service.getCoinsHistory().subscribe( (response) => { this.handleCoinsRespon ...

Differences Between Angular Module and Library

Exciting news - Angular has recently launched version 6 with a new CLI feature that allows you to generate libraries, which they are calling a "highly anticipated feature". From a business standpoint, I am left pondering the following questions: What is ...

Testing files outside of the project directory in Angular + Karma can present challenges in performing thorough analysis and evaluation

I have a file structure set up as follows: projects myproj - Angular App myproj-lib - Angular Library shared - shared code used in both the app and the library Both the App and Lib projects were created using Angular CLI (angular.json has not been mo ...

Find the difference between array_A and the documents in array_B using MongoDB's $match operator, and return the result as Array_C

I need to create an array_C that includes only the elements from array_A that are not present in array_B. My approach involves using $match in aggregate to specify array_B. For instance: array_A = [1, 2, 3] array_B = [2, 4, 6, 8, 10] array_C = [1, 3] I a ...

An error was encountered while attempting to utilize Google's Core Reporting API: Uncaught SyntaxError: Unexpected token <

I've been experimenting with Google's Core Reporting API and successfully implemented their provided demo. Now, I'm trying to integrate the code into my own project. My main tech stack includes AngularJS and PHP. I aim to keep it simple by ...

Issue encountered with the URL for the image in a JSON file following the utilization of multer for image uploads in a Node.js

Using multer to upload images for a blog website. After uploading an image with Postman, the filename is saved in the data.json file under "uploads\" directory. How can I save it as "uploads/" instead of "uploads\"? data.json { "id& ...

A guide on refreshing the dependencies list within Angular's node modules and package.json files

A close friend sent me the angular src folder, which I used to create a new Angular project. However, when I replaced my newly created src folder with my friend's and tried running the application using npm start, I encountered errors related to missi ...

Is it acceptable for a video to autoplay even if it is not connected to the DOM?

Consider the following three scenarios: document.adoptNode, document.importNode, and document.createElement with assigned properties. In all cases, the video autoplay feature is activated even when it's not connected to the DOM. This behavior diffe ...

What strategies can I employ to optimize this code in RXJS and Angular?

Is it possible to streamline these nested arrays for more efficient execution after all subscriptions have been completed? I believe there may be a solution involving the use of pipes, mergeMaps, concatMaps, etc. this.teams = [ { Assignments: [{Id: ...

Ways to resolve Cross-Origin Resource Sharing (CORS) issue encountered in Report

I am currently working on an Angular project and trying to render SSRS reports within the app by utilizing a specific package. The application is hosted at http://localhost:52698/ while the SSRS server resides on a different domain http:\ssrsserv ...

Potential Javascript timing problem encountered during webpage initialization – involving the implementation of a dynamic bootstrap progress

I have limited knowledge of javascript, but I stumbled upon this amazing fiddle that I would like to incorporate into my project: http://jsfiddle.net/5w5ku/1/ The issue I am facing is that I want it to persist for a duration of ten minutes. Despite atte ...

Inspecting every element within an array and indicating a negative outcome if any item is not a string

I'm currently working on a function called 'every' that takes in an array and a callback function as arguments. The purpose of the callback function is to determine if all elements in the array meet a certain condition. In my case, I want th ...

I'm encountering issues with undefined parameters in my component while using generateStaticParams in Next.js 13. What is the correct way to pass them

Hey there, I'm currently utilizing the App router from nextjs 13 along with typescript. My aim is to create dynamic pages and generate their paths using generateStaticParams(). While the generateStaticParams() function appears to be functioning corre ...

Why is the Twitch api map function returning nothing, while the console log is showing output?

Presently, my Nextjs page is making multiple Twitch API calls successfully and displaying the correct data. However, one of the mapping functions is failing to render anything on the page, even though the console log shows the data. Although I am relativel ...

Encountering a Next.js installation error due to the inability to locate the module fs

Having trouble with the installation of a new Next.js 14 app. I've searched on Google and Stack Overflow but haven't been able to find a solution. I'm stuck at this point. Can anyone offer some assistance? What I have attempted: npx creat ...

Next.js encountered an error while trying to locate the flowbite.min.js file for Tailwindcss and Flowbite, resulting in a

I'm having an issue with integrating the flowbite package with TailwindCSS in my Next.js application. Despite configuring everything correctly, I am encountering an error when adding the flowbite.min.js script: GET http://localhost:3000/node_modules/f ...

The initial function that gets executed in the lodash chain is tap()

When using lodash chain to perform actions synchronously, I encountered an issue where .tap() is executed before the desired stage. I have been unable to find a solution using promises. I expected lodash chain to ensure actions are carried out in a synch ...

Looking for tags similar to stackoverflow?

Is there a way to create a search box similar to the one in Tags where tag names are displayed immediately upon entering without pressing enter key? Could anyone provide me with a script or tutorial on how to achieve this? Is it done using JavaScript or j ...

Does the message "The reference 'gridOptions' denotes a private component member in Angular" signify that I may not be adhering to recommended coding standards?

Utilizing ag-grid as a framework for grid development is my current approach. I have gone through a straightforward tutorial and here is the code I have so far: typography.component.html https://i.stack.imgur.com/XKjfY.png typography.component.ts i ...