What is the best way to generate an array capable of storing elements with various data types from different interfaces?

I'm grappling with 2D arrays in typescript and have a query about it.

My goal is to craft an array that holds arrays where each element boasts a distinct data type, but all these elements correspond to different interfaces.

In the illustration below, you can observe four variables (elements) - member, publication, research, and courses sequentially. These represent the Member[], Publication[], Research[], and Course[] interfaces respectively.

this.answer = [this.member,this.publication,this.research,this.course]; 
I attempted the same approach, but unfortunately, it didn't yield the desired outcome. How can I store variables with varying interface characteristics in the 'this.answer' variable?

Post experimentation, I noticed that elements like 'this.member' carry values correctly, yet there seems to be an issue when placing these elements into 'this.answer'.

Thank you!

import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Subject, Observable } from 'rxjs';
import { MemberService } from 'src/app/services/member.service';
import { Member } from 'src/app/models/member';
import { PublicationService } from 'src/app/services/publication.service';
import { Publication } from 'src/app/models/publication';
import { ResearchService } from 'src/app/services/research.service';
import { Research } from 'src/app/models/research'; 
import { CourseService } from 'src/app/services/course.service';
import { Course } from 'src/app/models/course';

@Component({
  selector: 'app-survey',
  templateUrl: './survey.component.html',
  styleUrls: ['./survey.component.scss']
})

export class SurveyComponent implements OnInit {

 @Input() public renderPage;

  array1 : string[] = ['member','publication','research','course','event','banner'];
  answer;
  ren;

  member : Member[]=[];
  publication :Publication[]=[];
  research : Research[]=[];
  course : Course[]=[];
  
  constructor(
    public modal: NgbActiveModal,
    private ms: MemberService, 
    private ps: PublicationService, 
    private rs: ResearchService, 
    private cs: CourseService) { 

    this.renderPage = this.renderPage;
  }


  ngOnInit(): void {

    this.ms.getAll().subscribe(member => {
      this.member = member.sort((a, b) => a.index - b.index);
    });
    this.ps.getAll().subscribe(publication => {
      this.publication = publication.sort((a, b) => a.id - b.id);
    });
    this.rs.getAll().subscribe(research => {
      this.research = research.sort((a, b) => a.id - b.id);
    });
    this.cs.getAll().subscribe(course => {
      this.course = course.sort((a, b) => a.id - b.id);
    });

    //I have a problem in this code..!!
    this.answer = [this.member,this.publication,this.research,this.course]; 
    
    //this.answer1.forEach((element,idx)=>console.log(idx+ '||'+ element));

    this.array1.forEach(
      (element, idx) => {
        if(element === this.renderPage){
          this.ren = this.answer[idx];
        }
      }
    );
  }
  
}

The unique definitions of the four interfaces stand out here. Each interface hosts diverse variables specific to its structure.

export interface Member {
  id: number;
  name: string;
  role: string;
  degree: string;
  interest: string;
  employment: string;
  email: string;
  website: string;
  enrolled_year: number;
  enrolled_month: number;
  graduation_year: number;
  is_alumni: boolean;
  image_path: string;
  image_org_name: string;
  index: number;
  updated?: boolean;
}

Answer №1

Implementing union types in Typescript is simple, just follow this example:

const data: Array< Employee|Project|Product|Task> = []

To dive deeper into union types, refer to the official Typescript documentation here: Union Types

Answer №2

It seems like utilizing a dictionary with the forkJoin operator could provide an efficient solution to your issue. By doing so, you can avoid mixing asynchronous and synchronous code within the ngOnInit method.

Ensure that you are using version Rxjs 6.5.

Once all data sources emit a value and complete their operations, you can destructure the response object and apply your logic without needing to concern yourself with the order of the array elements.

forkJoin(
  // With RxJS 6.5+, we can utilize a dictionary of data sources
  {
    ms: this.ms.getAll(),
    ps:  this.ps.getAll(),
    rs: this.rs.getAll(),
    cs: this.cs.getAll()
  }
).subscribe(({member, publication, research, course}) => {
  // Your custom code goes here
})

Check out the forkJoin documentation

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

Creating a preview of a document with client-side scripting

I have been developing a feature that requires generating a preview in a popup for various file formats including PDF, Word, and Excel. I was able to achieve this by converting the files using Aspose.Words and Aspose.Cells. Here is the code snippet: publ ...

When attempting to transfer data from the parent component to child components, the data is appearing as undefined in the display

I have been working on passing data from a parent component to child components, but I keep encountering an issue where the data is showing as undefined. Below is the code snippet: Parent Component In this section, I have declared the variable part_data ...

Merging LEFT with SEARCH and REGEXREPLACE

As I assist someone, my goal is to extract only the cancer name from a column, excluding "Deaths -". In Column A, each entry follows this pattern, with each string in its own row... Deaths - Prostate cancer - Sex: Both - Age: Age-standardized (Rate) Death ...

Converting Json Arrays to Rows in Postgres with the Power of Lateral Joins

In the details field of my table, I have two JSON Arrays that I need to query and evaluate similarly to how I do in another relational table. { "city": "London", "name": "Sainburry", "quantities": [112, 145, 222, 122, 124], "prices": [4, 4 ...

What causes the module declaration in the .d.ts file to fail in an Angular application?

I have recently created a file named global.d.ts within the src folder and it contains the following content: declare module 'ol-contextmenu'; Despite my efforts, placing the file in the root directory or in node-modules/@types did not solve the ...

Javascript code for identifying objects in an array with specific properties and values

I have a collection of objects. Each object contains a boolean property named available, along with various other properties. While I am aware that the available property is present, the rest of the properties are unknown. For example: var myObjects = [ ...

Execute a function once an observable variable has been successfully initialized

I'm currently putting together a chat application using socket.io in Angular. I've encountered an issue where I can't seem to execute a particular code or function right after an observable variable is initialized through subscription. The i ...

Reassigning the memory of a string array in C and creating new strings

Can anyone help diagnose the issue in this code? I'm trying to resize an array of char** and then allocate memory for new strings (char*). void resizeArray(char*** array, int* p_capacity) { int index; int previousCapacity; char **temporar ...

Toggle the display of input fields based on radio button selection in Angular 2

We want to dynamically display additional input fields based on the selected radio button. Radio <div class="form-group"> <label>What would you like to evaluate?</label> <div class="radio"> <label> ...

Guide for triggering an exception when the format of one object does not match another object

When reading user input objects, it is important that they are well-formed. This means that the input objects may not have any key or sub-structure that is not defined in the interface. What is the best way to handle an exception if a user provides an in ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...

Sending an Array retrieved from a Facebook Graph API response via AJAX to a PHP script

Greetings! I'm currently in the process of developing a Facebook Canvas App and am facing some challenges with the Invite Friends feature. While my multi-friend selector is functioning well and sending invites as expected, I now aim to provide a rewar ...

Issue with angular oidc-client library's automaticSilentRenew functionality

I'm currently implementing oidc authentication using "oidc-client" version 1.10.1. Below is the configuration I have set up for the userManager: const settings = { authority: (window as any).__env.auth.authority, //OAuth 2.0 authorization end ...

Accordion's second child element experiencing issues with grid properties

I have set the parent element display:"Grid" and specified the gridColumnStart for my child elements as shown below. It seems to be working correctly for the first child element, but not for the second one. Please find my code attached: return ( ...

Tips for integrating external libraries (npm packages) in Ionic 4 applications

With the changes in Ionic 4, I am seeking a definitive guide on implementing third party libraries, such as "rss-parser". I have reviewed this article which seems to be the latest resource on the topic: https://ionicframework.com/docs/v3/developer-resour ...

Difficulty recognizing left click on onmouseup and onmousedown events in React with TypeScript

I am experiencing an issue with my code that is meant to update the mousePressed variable accordingly when the mouse button is pressed and released. Surprisingly, it works as expected for right-click and middle-click events but not for left-click. The ev ...

Connecting peers to servers using WebRTC

While attempting to set up a peer-to-server connection with WebRTC, I struggled due to the lack of TypeScript types in node-webrtc. This made it difficult to add collaborators and disrupted the codebase. Is there an alternative method for establishing a ...

Upgrade from AngularJS to the latest version of Angular, version 8

I'm trying to convert this AngularJS code into Angular 2+, but I'm having some trouble. Any ideas on how to do it? I've searched around, but this specific line is confusing me. scope.variable.value = event.color.toHex() Old Code: functi ...

Tips for transforming an image into a data array similar to MNIST

I am in the process of developing a neural network that can accurately identify numbers from the MNIST dataset. To facilitate this task, I created a GUI using tkinter where I can manually draw numbers. After implementing some code I found on Stack Overflow ...

Angular 8 combined with Mmenu light JS

Looking for guidance on integrating the Mmenu light JS plugin into an Angular 8 project. Wondering where to incorporate the 'mmenu-light.js' code. Any insights or advice would be greatly appreciated. Thank you! ...