Properties in a model class in typescript that share common characteristics

I need a data model class that can store identical information for two individuals simultaneously. For instance:

export class People {
    constructor(
        public person1Name: string = '',
        public person1Age: number = 0,
        public person1Game: string = '',
        
        public person2Name: string = '',
        public person2Age: number = 0,
        public person2Game: string ='',
    ){}
}

This class holds the same details (name, age, game) for two people.
Although I could use a generic person model class, the issue is that I always receive precisely two sets of individual's information from an Angular service to the component.
With a generic person class, I would have to pass an array of objects like:

Array: [person1, person2]

In such a scenario, it would be challenging to handle in both the service and the component since I utilize the information differently.
More importantly, I transmit details of two individuals from the service through an observable.

Therefore, my question is, is it possible to create a model class that captures the same information for two individuals as illustrated above? as I prefer to avoid using an array of objects..
Thank you in advance.

Answer №1

An example of using an interface to define a data type for individuals without actually creating instances.

export interface Individual {
  id: string;
  name: string;
  age: number;
  interest: string;
}

Here is a simplified demonstration:

@Component({...})
export class SampleComponent implement OnInit {
  individuals: Individual[] = []; // initialize an empty array

  constructor(private dataService: DataService) {}
 
  ngOnInit(): void {
    const person1 = this.createIndividual('Alice Smith', 30, 'Reading');
    const person2 = this.createIndividual('Bob Johnson', 25, 'Gaming');

    this.individuals = [person1, person2]; // add individuals as needed

    this.dataService.sendIndividuals(this.individuals).subscribe((response) => {
        response.forEach(person => console.log('Received Person:', person));
    })
  }

  createIndividual(name: string, age: number, interest: string): Individual {
    return {
      id: 'unique-id-for-each-person',
      name,
      age,
      interest
    };
  }
}
@Injectable({...})
export class DataService {
   constructor(private http: HttpClient) {}
  
   sendIndividuals(individuals: Individual[]): Observable<Individual[]> {
     return this.http.post<Individual[]>('endpoint', individuals).pipe(
        map(response => // perform operations on response)
     );
   }
}

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

Simple steps to make an Angular Material mat-card expand to full screen

Currently, my goal is to create a portal-style page layout using Angular Material. This layout will feature a grid of cards where each card can be expanded to take up the majority of the visible page, covering all other cards that are not in focus. The car ...

What methods are available to pass a variable value between two components in Angular 2?

I've been experimenting with Angular2 and recently created a component called appmenu using angular cli. The code in appmenu.html looks like this: <ul> <li (click)="menuitem1()">Menu Item 1</li> <li>Menu Item 2</li> ...

Angular2 - Unresolved Promise error: ViewContainerRef provider not found in dynamic template

I am currently working on implementing a dynamic component feature. In order to achieve this, I am utilizing three classes - LayoutComponent, MenuService, and DynamicService. The LayoutComponent is responsible for calling the MenuService method to carry ou ...

Is it possible to swap images by clicking on them?

Let's say I'm working with 3 images. Image A, B and C. A is the main image initially. If I click on image B, it will become the main image and image A will take its place in the old position. The same condition applies when B is the main image a ...

Splitting Ngrx actions for individual items into multiple actions

I'm currently attempting to create an Ngrx effect that can retrieve posts from several users instead of just one. I have successfully implemented an effect that loads posts from a single user, and now I want to split the LoadUsersPosts effect into ind ...

Angular 6: Sending Back HTTP Headers

I have been working on a small Angular Application for educational purposes, where I am utilizing a .net core WebApi to interact with data. One question that has come up involves the consistent use of headers in all Post and Put requests: const headers = ...

Utilizing a d.ts Typescript Definition file for enhanced javascript intellisene within projects not using Typescript

I am currently working on a TypeScript project where I have set "declaration": true in tsconfig.json to generate a d.ts file. The generated d.ts file looks like this: /// <reference types="jquery" /> declare class KatApp implements IKatApp ...

What is the best way to create a type guard for a path containing a dynamic field

In certain scenarios, my field can potentially contain both a schema and an object where this schema is defined by key. How can a guard effectively tackle this issue? Below is an example of the code: import * as z from 'zod'; import type { ZodTy ...

Ways to transmit information or notifications from a service to a component

Currently, I am utilizing Angular 6 and have the upload file control on three different screens (three various components). Each of these screens calls the same method UploadFile(). The main issue arises when I need to make any changes to this method, as ...

Angular Material: Setting the Sidenav/Drawer to Automatically Open by Default

I am currently utilizing the Angular Material Sidenav component within my project. Upon serving the webpage, I encounter an issue where the sidebar is not visible initially (as shown in the first image). However, after resizing the browser window for som ...

Using TypeScript with React: Automatically infer the prop type from a generic parameter

I've developed a component that retrieves data from an API and presents it in a table. There's a prop that enables the fetched value to be displayed differently within the table. Here's how I currently have the prop types set up: // T repres ...

Leverage tsconfig.json for TypeScript compilation in Vim using the Syntastic plugin

How can I configure the syntastic plugin in vim to provide live error checking for TypeScript files using tsc? Currently, even though I have tsc set up in vim, it doesn't seem to be using the closest parent's tsconfig.json file for configuration. ...

The input tag loses focus after its value is updated using a class method in Angular 8.x

Currently, I am working on integrating a credit card payment method and formatting its number through specific methods. Here is how it is done: HTML <div class="form-group" *ngFor="let formField of cardFields; let cardFieldIndex = index;"> ...

When a Discriminated Union in Typescript includes a value in a function parameter, it resolves to 'any'

Both of these examples overlook the parameter type in the onSelect function... TypeScript indicates that if clearable is not provided, value is considered as any. I'm stuck. I've tried both with and without a generic, but no luck. Can anyone ass ...

Issue with TranslateModule Configuration malfunctioning

I have put together a file specifically for managing ngx-translate configuration: import { Http } from '@angular/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { TranslateLoader, TranslateModu ...

What is the best way to first identify and listen for changes in a form

In Angular, there are reactive forms that allow you to track changes in both the complete form and specific fields: this.filterForm.valueChanges.subscribe(() => { }); this.filterForm.controls["name"].valueChanges.subscribe(selectedValue => { }); ...

Replace i18next property type in React for language setting

We have decided to implement multilanguage support in our app and encountered an issue with function execution. const someFunction = (lang: string, url: string) => any If we mistakenly execute the function like this: someFunction('/some/url', ...

When using Next.js or Express, a TypeScript project will seamlessly integrate as a local dependency during runtime or when building

I am currently developing a project in TypeScript using Next.js, and I've come across a peculiar issue where the project is automatically including itself as a local dependency in the package.json file. Here is an example of what my package.json file ...

Error encountered: The property 'localStorage' is not found on the 'Global' type

Calling all Typescript enthusiasts! I need help with this code snippet: import * as appSettings from 'application-settings'; try { // shim the 'localStorage' API with application settings module global.localStorage = { ...

Developing a project using npm and Node.js with Typescript has been smooth sailing so far. However, an issue has arisen

Recently, I came across a helpful guide on setting up a Node.js project in Typescript on this website: https://basarat.gitbooks.io/typescript/docs/quick/nodejs.html The guide also provides instructions for auto-recompilation upon changes when using npm st ...