I aim to display interconnected information from various APIs in a cohesive manner

I am working with two APIs:

component.ts

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);
  }

Both sets of data have the same ID, and I aim to display visits (from the first API) and nights (from the second API) side by side in a table: component.html

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

Unfortunately, with my current code, I'm only able to display either nights or visits randomly in each column.

Answer №1

Incorporate the Promise.all() function to synchronize the responses from both APIs, providing a more efficient solution.

Answer №2

Harness the power of rxJS by utilizing forkJoin. This function allows you to combine multiple observables into one.

import { forkJoin } from 'rxjs';

ngOnInit(): void {
  forkJoin({
    countries: this.getQueryCountriesList(),
    nights: this.getQueryNights()
  }).subscribe(({countries, nights}) => {
      this.countryDatas = countries;
      this.nightDatas = nights;
  });

So, what exactly is happening here? Using forkJoin, you ensure that both observables are emitted before combining their data into a single object.

Answer №3

If you are looking to synchronize the emissions of two observables before processing their values, you can make use of the combineLatest operator from rxjs. This operator will ensure that both observables have emitted at least one value before proceeding to combine those values into an array:

import { combineLatest } from 'rxjs';
 
ngOnInit(): void {
    queryCountriesList$ = this.getQueryCountriesList();
    queryNights$ = this.getQueryNights();
     combineLatest([queryCountriesList$,queryNights$])
    .subscribe(([queryCountriesList, queryNights]) => 
    {
        // process your values here
    }
}

Answer №4

Utilize the combineLatest feature from RxJS operators. For more information, you can check out this link

import { combineLatest, of } from 'rxjs';
import { map } from 'rxjs/operators';

const weight = of(70, 72, 76, 79, 75);
const height = of(1.76, 1.77, 1.78);
const bmi = combineLatest([weight, height]).pipe(
  map(([w, h]) => w / (h * h)),
);
bmi.subscribe(x => console.log('BMI is ' + x));

// Output:
// BMI is 24.212293388429753
// BMI is 23.93948099205209
// BMI is 23.671253629592222

For your specific case:

const combined = combineLatest([
  getQueryCountriesList(),
  getQueryNights(),
]).pipe(
  map(([countries, nights]) => {
    // Insert your custom logic to combine objects and remember to return the final value
  })
);
combined.subscribe((x) => console.log("The final result is " + x));

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

What is the proper way to utilize ngIfElse in Angular 9?

Currently, I have a list of posts that are being fetched using services and displayed on the UI. There is a search box with an ID field specified in it. My goal is to render the post in a card if the provided ID exists. This functionality is working well. ...

Explaining the process of defining an object type in TypeScript and the conversion from JavaScript

Currently, I am attempting to enhance the background of a React website developed in typescript (.tsx) by incorporating particles. My approach involves utilizing the particle-bg component available at: https://github.com/lindelof/particles-bg However, whe ...

What is the best way to extract a particular key value from a JSON object?

I am completely new to the world of APIs and just starting out with JavaScript. My goal is to retrieve the status of a server from a server hosting panel using an API. In order to achieve this, I need to log in by making a request to /API/Core/Login, extra ...

Fade-in loader with centered placement on the full page

As a newcomer to programming, I wanted to implement a loader that displays a centered loading animation when the page loads or refreshes. The animation should gray out and fade the entire page until it fully loads. I've managed to get everything else ...

Clicking on a radio button can trigger the selection of another radio button

I'm currently working on a form that includes 8 radio buttons - 4 for System A and 4 for System B. The options for the buttons are CF, ISO, ISO-B, and NW. My goal is to create a functionality where selecting a radio button in System A automatically se ...

Adjust the viewport width based on the width of the device

Having difficulty adjusting the meta tag viewport content width based on device width, I am struggling to achieve my desired outcome. Here is the code snippet I have been working with: Code snippet: <meta id="viewport" name="viewport" content="width=d ...

AngularJS module is experiencing issues with loading properly

Can someone please help me understand what the issue is? I am new to AngularJS and may have overlooked something. Below is my simple HTML code: <!DOCTYPE html> <html> <script type="text/javascript" src="angular.js"></script> ...

Issue with retrieving JSON objects in Next.js

I've been developing a straightforward crypto price tracker using the coingecko API. At the moment, my code is unable to retrieve any of the JSON objects from the API link, and curiously, no errors or warnings are being generated to indicate what the ...

Encountering an unexpected token error while building an Angular4 --prod project that involves Three

Encountering an error while trying to build an Angular4 project in production with the following command: node --max_old_space_size=8192 'node_modules/@angular/cli/bin/ng' build --prod --output-hashing=al Error: ERROR in vendor.422622daea37e ...

Retrieve the current element when the key is released and send it as a parameter to a different function

Imagine a scenario where my website contains textbox elements that are dynamically generated, each with the class 'mytxt'. <input type="text" class="mytxt" /> <input type="text" class="mytxt" /> <input type="text" class="mytxt" /& ...

Identifying an Object by Clicking with the Mouse in three.js

After successfully loading 3 external models into my scene using the json loader, I am now trying to retrieve the name of the clicked model/object. Below is the code snippet that I used to load the models: var object_material = new THREE.MeshBasicMateria ...

Error message in node.bcrypt.js: 'No callback function provided; result is undefined.'

Currently, I am enrolled in Mosh Hamdani's Mastering React Course and have encountered some challenges with back-end development. The most recent issue is an error message stating: “undefined No callback function was given” when attempting to regi ...

Removing double double quotes for Javascript

My problem involves a string that represents longitude/latitude in the format of dd°mm'ss''W (note 2 single quotes after ss). To convert this string into its decimal representation, I am using the following code snippet: function dmsTodeg ...

How to overcome the issue of Vue.js mobile router-link being blocked by v-on:mouseover

Here is a for list snippet: <li class="projects-item" v-for="project in filteredProjects" :key="project.id" v-on:mouseover="displayHoverInfo($event, project)" v-on:mouseleave="hover = false" > <router-link v-bind:to="'/project/ ...

Objects That Are Interconnected in Typescript

I have been delving into TS and Angular. I initially attempted to update my parent component array with an EventEmitter call. However, I later realized that this was unnecessary because my parent array is linked to my component variables (or so I believe, ...

Having trouble figuring out how to display a tooltip using the show() method in @teamhive/ngx-tooltip?

I am looking for a way to toggle this tooltip on and off as I navigate with my mouse, especially because it is attached to nested elements. Although I can detect cursor movement for other purposes, I need a solution for controlling the tooltip display. Ac ...

What is the correct way to effectively share data between components using a service?

I've been diving into learning Angular 2 and successfully implemented data sharing between sibling components using input/output functions. Check out my working example here. // Our root app component import {Component, NgModule} from '@angular ...

Steps to configure npm start for an electron application using "babel-node --presets es2015,stage-3"

I've been experimenting with getting my npm start to work properly for electron. Typically, you would start a non-distributed app with electron . or ./node_modules/.bin/electron .. However, due to my use of NodeJS v8.4.0 and ES6/7 syntax, my npm start ...

Three.js experiences a memory leak issue

We are currently working on a single page app where users can switch between multiple Three.js apps. However, we have observed a continuous increase in memory usage by the tab. There is no memory leakage in our app and it appears that Three.js variables ar ...

Having trouble getting the convert-multiple-files npm package to function properly on an Elastic Beanstalk environment running Amazon Linux

Following a successful deployment, I encountered an issue with my file conversion script when attempting to convert files as outlined in the documentation. The script works flawlessly on both a local Windows 10 machine and Ubuntu 20.04 LTS. const { conv ...