how can I retrieve an array of nested objects from two interrelated tables that have a one-to-many relationship using

Hey everyone, I have a scenario where I'm working with 2 MySQL tables: itemsClass which holds various classes, and itemType which links to itemClass and contains type values for a specific class.

My goal is to create a service that returns an Observable<Item[]>, by combining two http.get Observables in accordance with this interface:

interface Item{
 itemcClassId:any; //itemClass.id, fetched from itemClass select query
 itemClassName:any; //itemClass.name fetched from itemClass select query
 itemTypeValue?:any;    //from itemType select, if itemType has only one value related to the first table's class
 itemTypeValues?:any[]; //if there are multiple values in the itemType table
}

After extensive searching, I found a code structure similar to this:

getEmploye(name: string): Observable<any> {
    return this.getClass(name).pipe(
      switchMap((response) => {
        return forkJoin(of(response),this.getType(class.id);),
               map(res=>{
                 return {...res[0],values:...res[1]}
               })
      })
    ) 
  }

However, this code snippet only returns a single item whereas I need an array of items. Any suggestions?

Thanks in advance!

EDIT: The code I posted was generic and not customized. A tailored version that retrieves just one item would involve something like this:

getItem(id: number): Observable<Item> {
    return this.http.get(url_to_ItemClass_rest_api).pipe(
      switchMap((item) => {
        return forkJoin(of(item),
this.http.get(url_to_ItemType_rest_api_filtered_by_foreign_key_item.id/);),
               map(res=>{
                 return {...res[0],values:...res[1]}
               })
      })
    ) 
  }

Answer №1

The use of forkjoin is outdated in this scenario. It is now necessary to pass an array:

forkjoin([of(item),
this.http.get(url_to_ItemType_rest_api_filtered_by_foreign_key_item.id/)])

If you desire a single return containing both key and value, you can achieve it like so: const ret = { ...res[0], values: res[1] };

  acquireEmployee(id: number): Observable<any> {
    return this.retrieveClass(id).pipe(
      switchMap(item => {
        return forkJoin([of(item), this.getType(item.id)]).pipe(
          map(res => {
            const result = { ...res[0], values: res[1] };
            return result;
          })
        );
      })
    );
  }

For handling an Array, consider implementing the following approach:

retrieveClass(name: number): Observable<Array<{id: string}>>

getType(classId: string): Observable<Array< string >>

acquireEmployee(id: number): Observable<any> {
    return this.retrieveClass(id).pipe(
      switchMap(items => {
        const forkRequest: Array<any> = [of(items)];
        items.forEach( item => forkRequest.push(this.getType(item.id)));

        return forkJoin(forkRequest).pipe(
          map((res: Array<any>) => {
            const resultList: Array<{id: string, values: Array<any>}> = [];
            res.forEach((item: any, index: number) => {
              if (index > 0) {
                const responseObj = { id: res[0][index - 1].id, values: item };
                resultList.push(responseObj);
              }
            });
            return resultList;
          })
        );
      })
    );
  }

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

Adding curly braces around values when using Angular's form group patchValue method

I have been working on a dynamic form using form builder in order to update form data dynamically. I have created a function that iterates through keys in an object and patches the form values based on matching key names. While this approach works for most ...

Utilizing the PATCH method with Dropwizard to remove a designated item from a list that is a part of another list

Currently, I am working on developing a PATCH API method that can remove a specific element from a list of items. This list of items is an integral part of the Menu class in my project. Unfortunately, there is a scarcity of Dropwizard resources available o ...

What is the proper way to utilize a service within a parent component?

I need assistance with setting up inheritance between Child and Parent components. I am looking to utilize a service in the Parent component, but I have encountered an issue. When attempting to input the service in the Parent constructor like this: expor ...

Tips for sharing NPM packages on GitHub and enabling public downloads without requiring authentication

Lately, I've been working on developing NPM packages for the company I'm employed at. We've successfully published two Angular component packages. However, we faced an issue when the Azure DevOps build pipeline failed to download these pack ...

Exploring Typescript: Uncovering the Secrets of the navigator.connection Property

I am trying to access the NetworkInformation interface by using a simple TypeScript function like the one shown below: private checkNetworkConnection(): void { const connection = Navigator.connection || navigator.mozConnection || navigator.webkitConn ...

Using mat-select along with formControl to establish the default value

I'm struggling to assign a default value to my formControl, but it doesn't seem to be working as expected. select-hint-error-example.ts export class SelectHintErrorExample { animalControl = new FormControl('', [Validators.required]) ...

Understanding the significance of the term "this" in Typescript when employed as a function parameter

I came across a piece of TypeScript code where the keyword "this" is used as a parameter of a function. I'm curious to know the significance of this usage and why it is implemented like this in the following context: "brushended(this: SVGGElement) {". ...

Can someone provide an explanation of the Typescript peerDependencies in Angular, specifically comparing versions tslib 1.* and 2.3.*?

I am in the process of starting a new angular project, but I'm facing difficulties in importing the localStorage feature. I referred to an existing project that utilized localStorage in the following way: import { Injectable } from '@angular/core ...

Ways to transfer data from TypeScript to CSS within Angular 6

Trying to work with ngClass or ngStyle, but I'm struggling with passing the value. Here's my current code: strip.component.ts import { ... } from '@angular/core'; @Component({ selector: 'app-strip', templateUrl: &apo ...

Guidelines for utilizing a loader to handle a TypeScript-based npm module

I am currently facing a challenge with my React and JavaScript project as I attempt to integrate an npm module developed with TypeScript. The issue lies in configuring my project to compile the TypeScript code from this module, resulting in the error messa ...

Struggling with making updates to an interface through declaration merging

I am encountering challenges with implementing declaration merging on an interface from a library that I created. An example illustrating the issue using StackBlitz can be viewed here: https://stackblitz.com/edit/typescript-qxvrte (issues persist in both ...

Retrieve the current step index in Angular Material Design Stepper

In my endeavors to retrieve the selected step within a component utilizing Angular Material Design stepper, I am encountering some issues. My current approach involves using the selectedIndex property, but it consistently returns "1" instead of the desire ...

Encountering an error with type mismatch for style transform properties while using react-native-reanimated

Currently working with the following versions: "react-native": "0.59.10" "react-native-reanimated": "^1.3.0" using TypeScript Encountering a type error related to transform properties. const Example = () => { const { translationX, gestureHandler } = ...

Sending data with an Http POST request in Angular 2

I'm having difficulty with a POST request that I am trying to make: sendRequest() { var body = 'username=myusername&password=mypassword'; var headers = new Headers(); headers.append('Content-Type', 'applicat ...

NextJS VSCode Typescript results in breakpoints becoming unbound

I have been following the instructions provided by Next.js from their official documentation on debugging using Visual Studio Code found here: https://nextjs.org/docs/advanced-features/debugging#using-the-debugger-in-visual-studio-code When attempting to ...

Move on to a different screen in a React Component once the data has been fetched

Currently, I am delving into the world of React and TypeScript and attempting to utilize "react-router-dom" in order to create a login component that will interact with my backend server. Essentially, my goal is to develop a "Login" class that, upon form ...

An issue has occurred: Unable to locate a supporting object 'No result' of type 'string'. NgFor is only compatible with binding to Iterables like Arrays

I am attempting to utilize this code to post data from a web service. service.ts public events(id: string): Observable<Events> { ...... return this.http.post(Api.getUrl(Api.URLS.events), body, { headers: headers }) .map((re ...

Designing Angular 1 table row components with future migration to Angular 2 in consideration

Issue with AngularJS nested directives placement outside parent element Encountering the same challenge in my project using Angular 1.4, but I am also aiming to construct the rows as Angular 2 components which prevents me from using "replace: true". I am ...

Steps for associating ngclass with an observant value

Can you bind to an Observable<enum> like this in Angular? <a [ngClass]="{selected: (mapToolBarMode$ | async) === 0 }" /> or <a [ngClass]="{selected: (mapToolBarMode$ | async) === MapMode.Pan }" /> where the observable is named mapTool ...

Revitalize access token with Keycloak in Javascript

I am currently working with keycloak-js version 8.0.1 and have a function called getToken that checks if the token is expired. If it is expired, the function refreshes it; otherwise, it returns the current token. The issue I am facing is that even though t ...