I am looking to display data in Angular based on their corresponding ids

I am facing a scenario where I have two APIs with data containing similar ids but different values. The structure of the data is as follows:

nights =

{
    yearNo: 2014,
    monthNo: 7,
    countryId: 6162,
    countryNameGe: "რუსეთის ფედერაცია",
    gender: 1,
    ageGroup: 2,
    nights: 26124560
},

visits =

{
    yearNo: 2020,
    monthNo: 10,
    countryId: 5967,
    countryNameGe: "აზერბაიჯანი",
    tourType: 1,
    gender: 1,
    ageGroup: 1,
    value: 7502768
},

My goal is to display related data (based on matching countryIds) side by side in an HTML table.

This is how I am approaching it in my component.ts file:

ngOnInit(): void {
       this.getQueryCountriesList().subscribe(arg => {
         this.countryDatas = arg;
       });
       this.getQueryNights().subscribe(obj => {
        this.nightDatas = obj;
      });
........
......
  getQueryCountriesList(){
    return this.http.get<any>(this.APIUrl + "/Visitor?tourType="+ this.tourType +"&year=" + this.selectedYear + "&month=" + this.selectedMonth +"&gender=" + this.selectedGender + "&age="+this.selectedAge);
  }
  getQueryNights(){
    return this.http.get<any>(this.APIUrl + "/Nights?tourType="+ this.tourType +"&year=" + this.selectedYear + "&month=" + this.selectedMonth +"&gender=" + this.selectedGender + "&age="+this.selectedAge);
  }

Initially, I attempted the following approach, but encountered issues:

<tr *ngFor="let country of countryDatas; let nights; of: nightDatas">
    <th [id]="country.countryId + '1'">{{ country.countryNameGe }}</th>
    <td [id]="country.countryId + '2'">{{ country.value }}</td>
    <td [id]="country.countryId + '3'">{{ nights.value }}</td>
</tr>

Subsequently, I tried the following alternative:

const resulti = this.countryDatas.map((obj:any) => ({
    ...obj,
    ...this.nightDatas.find((o:any) => o.countryId === obj.countryId),
  }));

However, this resulted in an empty array being returned. What would be the best approach in this situation?

Answer №1

Combining two data objects within a subscribe function.

forkJoin waits for all responses before emitting data.

ngOnInit() {
    forkJoin({
      countriesData: this.fetchCountriesData(),
      nightsData: this.fetchNightsData()
    })
    .subscribe(({countriesData, nightsData}) => {
      mergedResult = countriesData.map((country:any) => ({
           ...country,
           ...nightsData.find((night:any) => night.countryId === country.countryId),
      }));
    });
  }

Answer №2

To accomplish this task, follow these steps:

for each item in countryDatas:
    if the id of the current item matches the id of nightDatas:
        assign the current item to similarDatas

Next, in your HTML file, include the following:

<th [id]="country.countryId + '1'">{{ similarDatas.countryNameGe }}</th>
    <td [id]="country.countryId + '2'">{{ similarDatas.value }}</td>
    <td [id]="country.countryId + '3'">{{ similarDatas.value }}</td>

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

MD Autocomplete Component: An Input Inside

Currently, I am working on implementing a feature where users can enter different search terms in an input field within Angular Material's autocomplete component. The issue arises when the user clicks on the input option as it closes the autocomplete ...

Exploring Appsetting Configuration in AppModule of Angular 8

I'm looking to update my configuration in the appsettings file by replacing a hardcoded string with a reference to the appsetting. Currently, I have this hardcoded value in appmodule.ts: AgmCoreModule.forRoot({ apiKey: 'testtesttest', li ...

Attempting to transmit JavaScript information to my NodeJS server

Having some trouble sending geolocation data to NodeJS through a POST request. When I check the console log in my NodeJS code, it's just showing an empty object. I've already tested it with postman and had no issues receiving the data. The probl ...

Tips for inserting a page break after every item in a loop in Visualforce when generating a PDF document

I need help with rendering a VF page as PDF. The VF page iterates over a list of account records using the repeat tag. I want to apply a page break for each element in the repeat tag. The code below is working, but it has an issue - it shows an empty PDF p ...

Issue with Angular 2 view not refreshing after receiving ipcRenderer.on event in Electron

Utilizing ipcRenderer to fetch the folder path from a browser dialog in my main.js. However, it is not updating the text string on my view for some unknown reason. I am aware that using setTimeout could potentially fix this issue (thanks Google!). Yet, e ...

I recently incorporated @angular/material into my project and now I am encountering a version compatibility issue

I am currently facing a versioning challenge in my Angular project. My goal is to operate on Angular 6, but despite trying various guides on how to reversion the project, I have been unsuccessful. Here is the output of my 'ng version' command: ...

When utilizing a Service through UserManager, the User variable may become null

Utilizing Angular 7 along with the OIDC-Client library, I have constructed an AuthService that provides access to several UserManager methods. Interestingly, when I trigger the signInRedirectCallback function from the AuthService, the user object appears ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

remain on the multi drop down page for a specified duration

I have created a dropdown menu with a second level drop-down page that is a form. Now, I want the second level drop-down page to stay open longer, so I have used the following JavaScript code: <script> var timer; $(".parent").on("mouseover", functio ...

Firestore experiencing difficulty fetching / showing data

For some reason, Firestore is unable to retrieve or display data from a Collection named data. This issue emerged after I attempted to simplify my code. Take a look at the code snippet: Filename: database.component.ts import { Component, OnInit } from & ...

The name is not found when using attribute, but it is found when using extends

Lately, I've encountered difficulties with creating large TypeScript modules, and there's one thing that has been puzzling me. Specifically, the following scenario doesn't seem to work: // file A.ts export = class A { } // file main.ts imp ...

What could be preventing the jQuery from showing the JSON response?

I am having an issue with a jQuery script that is supposed to pull a quote from an API in JSON format and display it on the page. However, for some reason, I am unable to retrieve data from the API. Can you help me figure out what is wrong here? Thank yo ...

Positioning the label for a Material-UI text field with an icon adornment when the shrink property is set

https://i.stack.imgur.com/E85yj.png Utilizing Material-UI's TextField, I have an Icon embedded within. The issue arises when the label "Your good name here" overlaps the icon instead of being placed beside it. This problem emerged after I included ...

Utilizing libraries in JavaScript

For a while now, I've been grappling with an issue related to importing modules into my main JavaScript script. I recently installed the lodash library via npm and I'm trying to import it into my main script so that I can utilize its functionali ...

Using formControlName with an Ionic2 checkbox allows for seamless integration of

Currently facing an obstacle with checkboxes in ionic2. Here is how I am using the checkbox: <ion-item> <ion-label>Agree</ion-label> <ion-checkbox color="dark" id="agree" name='agree' class="form-control" formContro ...

AngularJS Get request unable to fetch image URL due to receiving a "302 found" error

Trying to enhance my AngularJS app by incorporating an image from a random cat image site, using the URL received. Below is the snippet from my controller.js: 'use strict'; /* Controllers */ var catPath = "http://thecatapi.com/api/images/get? ...

Gain access to PowerBI reports effortlessly without the need to input any credentials

Seeking guidance on calling Power BI reports from an ASP.NET C# web application while passing credentials, specifically without utilizing Azure AD. Access has been granted to certain users in the Power BI Service workspace with view permissions. We aim t ...

ReactJs - The pagination feature in MaterialTable is malfunctioning, it is not displaying the correct

I am currently utilizing the Material-table plugin. It successfully displays the data, however, I am facing issues with Pagination and Row per Page dropdown functionality. When trying to click on the next button or select a number of rows, nothing happens. ...

Is it possible for AJAX to update a button's argument?

After successfully using AJAX to extract a data value from a button click, I am now looking to pass this value as an argument to another button on the same page. Is there a way to achieve this seamlessly? Sample code from test.html: <a href="#" onClic ...