Best Practices for Managing Arrays of Various Objects in Angular 9 HTTP Requests

As a newcomer to Angular and web development, I apologize in advance if my terminology or explanations are not accurate. Here is my issue:
I am working with Angular 9 and making http requests (get and post) to an API using the HttpModule. The response object (and post object) is a JSON object that contains an array of variable objects:

inputs: [
    {
      id: string,
      sT: string,
      stl: string,
      mCC: number
    },
    {
     id: string,      
     sT: string,
     val: string,
     dT: string
    }

  ]

I have learned that it's common practice to create interfaces for response objects in order to access their properties by name. I have done this for all other properties, including nested ones, but I'm facing an issue with the array above where the objects do not have the same attributes. So, I created an interface for 'Input' with optional attributes like this:

// Single interface with optional attributes

export interface Input {
  id: string;
  sT: string;
  dT?: string;
  val?: string;
  mCC?: number;
  stl?: string;
}

However, I feel that this may not be the standard way of typing this type of object. What would be the recommended practice to handle this situation 'Angularish way'? Is this more of a TypeScript question?

I would appreciate any guidance on best practices for handling this type of object, as I anticipate encountering similar scenarios frequently in the future.

Answer №1

When uncertain about the attributes that will be returned, one can define a general interface like this:

interface Input{
  [key: string]: any;
}

If certain elements will always be present, a more specific approach can be taken:

interface Input{
  id: string;
  name: string;
  [key: string]: string|number;
}

For scenarios where there is a limited random selection of elements, such as in the given example with six elements, the provided solution suffices.

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

Vanilla JavaScript - Utilizing a Function to Target DOM Elements

I'm working on selecting a DOM element in JavaScript without using jQuery. Here's the code I have: function ChooseElement(a, b, c, d, e) { c = a.charAt(0); d = a.substring(1); if (c == ".") { e = document.getElementsByClassNa ...

The alert function in the Ajax web method is malfunctioning

Every time I try to call the Ajax web method, I keep receiving a 'save error' message. However, the data is successfully saved to the database without any issues. I have checked for errors but couldn't find any. How can I display an alert sa ...

Utilize absolute positioning within Three.js to ensure that all objects are anchored at the 0,0,0 coordinate point

I am facing an issue where the solutions provided do not seem to work for me as I am new to Three.js. In my scene, I have several objects such as a map with each region represented by a separate object positioned on a plane. Here is an image of my setup: ...

What is the best way to retrieve an element from an array that was obtained via an http.get request?

Upon making an http get request in Angular, I received an array of Question objects. However, I am encountering an issue where I cannot access an element from it due to the error message: Cannot read property '0' of undefined. My assumption is th ...

Adding the <a> tag causes Superfish to malfunction

I've been struggling to get the latest Superfish menu code working with lists that include the <a> tag. I've double-checked everything, but it seems like I'm missing something obvious. Can anyone help me figure out what's wrong? ...

Typescript's default generic datatypes

I am currently working with a protractor list page object. By default, this object returns instances of ElementFinder, but there is a way to customize it to return instances of ComplexType like the following: class ComplexType { foo = 'foo'; ...

The issue arises when jQuery stops functioning properly following the second ajax call

I'm encountering an issue with my ajax request in asp.net mvc. It works fine for the first and second time, but then it redirects to a page instead of fetching the page via ajax. Below is the code snippet for my partial page: <script> var ...

Node.js is executing the CRON process twice

Within my Node.js application, I have set up a CRON job that runs every day at 10 AM to send push notifications to users. However, I am encountering an issue where two notifications are being sent to the user's device each time the CRON job is trigger ...

Utilizing JavaScript to Incorporate Node Packages

Sorry for the basic question, as I am fairly new to web development and JavaScript. I am trying to utilize a package that I installed via npm called shopify-buy by following the instructions provided at: The package is located in my node_modules director ...

Nested categorization in linq javascript

I have a JSON format that contains information about different people within various departments and sub-departments. var personArray = [ {name:"person1",code:"101011",mainDept:"mainD 1",dept:"dept1",SubDept:"Sub01"}, {name:"person2",code:"201012 ...

Adding an item to the collection

When I log my cartProducts within the forEach() loop, it successfully stores all the products. However, if I log my cartProducts outside of the loop, it displays an empty array. var cartProducts = []; const cart = await CartModel .fin ...

How can we delete data from an array in Angular by using checkboxes?

I am working with a mat-table that displays data fetched from an API. Here's a snippet of the table structure: <mat-table [dataSource]="dataSource$"> <ng-container matColumnDef="process"> <mat-header-cel ...

To enable RTL in TextField, please note that the JssProvider is only available in "react-jss/src/JssProvider" and not in "react-jss/lib/JssProvider"

Seeking help to convert LTR to RTL in the following code: <TextField id="date" label="EmployeeDate" type="date" onChange= ...

Store the running of a JavaScript file in memory

It seems highly unlikely that achieving the following is possible without expert confirmation: On page number 1, user and application data is requested as soon as the page loads. Page number 2 utilizes the same script, so requesting the same information w ...

Tips for effectively typing a collection of React wrappers in TypeScript

I encountered a situation in my team's application where we need the ability to dynamically compose component wrappers (HOCs) without prior knowledge of all the wrapper interfaces. This is mostly needed for swapping out context providers when renderin ...

What is the best way to transfer variables to a different page through a pop-up window?

I'm working with a function that converts the Id of the clicked element into a variable, then opens a new window with a different page. How can I access or utilize this variable on the newly opened page? var idToWrite = []; $(function(){ $(".szl ...

Web Inspector shows no trace of HttpOnly Cookies

My current project involves implementing user authentication for a website using the MERN stack, and I have opted to utilize JWT tokens stored as HttpOnly cookies. Interestingly, when I made the request via Postman, the cookie was sent in the "Set-Cookie" ...

The functionality of the material-table example is not functioning properly as expected

I came across a specific table on Material-UI's Table page that caught my attention for a project I'm working on. This particular table is labeled material-table (https://material-ui.com/components/tables/#material-table) and includes features li ...

Encountered a glitch while compiling Nestjs using typeorm

I encountered an issue when attempting to include the entity.ts in the project Here is the content of ts file: import { Column, Entity, PrimaryGeneratedColumn } from "typeorm" @Entity('Usuario') export class UsuarioIdentity { @Pr ...

How to Pass a JSON Object to a Child Component in Angular and Display It Without Showing "[Object

Need help with my API call implementation. Here's a snippet from my Input component: Input.html <form (submit)="getTransactions()"> <div class="form-group"> <label for="exampleInputEmail1"></label> <input type="t ...