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

Embedding a table row within an anchor element in Angular 4

Currently, I am facing an issue with a table that contains [routerLink] on each <tr>. This setup is preventing the "open link in a new tab" option from appearing when I right-click because there is no <a> tag. I attempted to enclose the table r ...

Exploring the world of React and Material Ui

As I delve into working with Material Ui in React, I am encountering difficulties when trying to customize the components. For instance, let's take a look at an example of the AppBar: import React from 'react'; import AppBar from 'mat ...

What is the best way to sort a union based on the existence or non-existence of a specific

My API response comes in the form of a IResponse, which can have different variations based on a URL search parameter. Here is how I plan to utilize it: const data1 = await request<E<"aaa">>('/api/data/1?type=aaa'); const d ...

Only the initial value is being processed in the for loop using Javascript

I am having issues trying to sum the values within a for loop sourced from my Django database using JavaScript. Currently, when I iterate through the loop, only the first value in the array is returned. I need assistance in finding a solution that allows ...

Angular service tested using the put method in a test scenario

Currently, I am delving into test cases using Jasmin and karma to enhance my skills. One interesting project involves creating an Angular service that updates records in a database. While I have experience creating test cases, I must admit that testing met ...

Refresh all tabs in the TabContainer

I have implemented multiple tabs using dojo on a web page, and I need to refresh the current tab every 5 seconds without refreshing the entire page. You can check out the code in this fiddle: http://jsfiddle.net/5yn2hLv9/4/. Here is an example of the code ...

Utilizing HTML injection to access both the Chrome API and global variables

I am currently developing a new Chrome Extension and am diving into the process for the first time. My extension involves injecting an HTML sidebar into web pages, adding JavaScript functions to the header, and allowing users to interact with buttons on th ...

Incorporating Copyleaks SDK into Angular: A Seamless Integration

Currently, I'm in the process of implementing the Copyleaks SDK with Angular to conduct plagiarism checks on two text area fields within an HTML form. Within the form, my goal is to incorporate two buttons: one to check for plagiarism on one text area ...

ways to access ng-model value within a directive

I recently developed a custom directive in AngularJS that utilizes the input type number with min-max and ng-model attributes. I made sure to use an isolated scope for the directive. However, despite setting up a blur event within the directive, I am encou ...

Is there a similar effect in jQuery? This is achieved using prototype

Simply click on the comments link. Observe how the comments smoothly appear, as if sliding down. Also, try clicking on 'hide' and see what happens. ...

"Enhance your website with captivating Javascript hover effects for

Can anyone assist me with incorporating the navigation hover effect seen on this website into my HTML/CSS project? The example site is built using a WordPress theme, but I am looking to apply that green effect to my own webpage and have the ability to cust ...

Tips for retrieving a value from fs.accessAsync function

I am currently working on verifying the accessibility of a specific file, folder, or directory for reading purposes. I have implemented the code below, which functions properly. However, there are a couple of aspects that I would like to inquire about: 1. ...

Is there a way to adjust the padding temporarily?

Important Note: Despite the misleading title of my question, it doesn't accurately reflect my actual query (sort of). Below is the code snippet in question: .one{ background-color: gray; } .two{ padding: 20px; } <div class = "one"> < ...

How can one properly extend the Object class in JavaScript?

I have a scenario where I want to enhance a record (plain Javascript object) of arrays with additional properties/methods, ideally by instantiating a new class: class Dataframe extends Object { _nrow: number; _ncol: number; _identity: number[]; co ...

Using knockout to retrieve the attribute value with an onClick event

Snippet of HTML View with attribute value 'Qref'. This is the sample HTML Code for binding Currently, I have manually inputted the Qref Attribute value <!--ko if:$parent.Type == 2 --> <input type="checkbox" data-bind="attr:{id: $data ...

During the build process, NextJS encountered an issue locating the constants.js module

I encountered an error while executing next build using next version ^10.2.3. I attempted to remove the node_modules and .next folders, then reinstalled dependencies with npm install && next build, but the issue persists. Error: Cannot find mod ...

Combine two columns into a single table column using HTML/CSS and JavaScript with the help of Datatables

I utilize the DataTables library from https://datatables.net/ to create sortable and searchable tables on my website. However, my table becomes too wide due to the numerous columns it contains. I am looking for a way to condense the width by merging relate ...

Locate and eliminate the item containing specific content

There are many <p> &nbsp </p> tags scattered throughout the description. I need to locate and delete any tags that contain only &nbsp. The description is enclosed in a container with the class name of desc_container. Below is an exampl ...

What is the method for retrieving post ID with the Google Feed API?

I am currently utilizing two different JS codes to dynamically load posts from my Wordpress website: Code 1: JSON API <script src="http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=listPosts" type="text/javascript">& ...

What could be causing the lack of re-rendering in children components using redux-form?

When the parent component sends data, the children components do not re-render automatically. Re-rendering only occurs when a key is pressed on an input element. SMART User values from the state are sent by the smart component. If we add console.log(this. ...