Retrieving information from a JSON API using Angular with Typescript

Currently, I am dealing with an API JSON to fetch a list of countries, followed by a list of states, and then cities within that state and country. The challenge lies in the second API call that I make. In the beginning, I load a list of continents and then proceed to retrieve the lists of countries. However, the issue arises when I have to iterate over the continents to obtain the countries. This requires me to concatenate or merge multiple lists into one, something I am struggling with. Below is the code snippet of my progress so far:

pegPaises2(): void {

    let count = 0;
    console.log('We are in action!');

    this.httpp.get('http://www.geonames.org/childrenJSON?geonameId=6295630')
    .subscribe((resContinents: Response) => {

        resContinents.json().geonames.forEach(element => {
          this.httpp.get(`http://www.geonames.org/childrenJSON?geonameId=${element.geonameId}`)
            .subscribe((resCountries: Response) => {

              resCountries.json().geonames.forEach(elementt => {

                count = count + 1;

                const Country = new COUNTRY;
                Country.geonameId = elementt.geonameId;
                Country.name = elementt.name;


                console.log(count, Country);

              });
            });
        });
    });
}

I believe using an observable or an array could be advantageous. I attempted to use push but haven't come across any understandable examples (I am a beginner).

Answer №1

You have the ability to chain your API calls (continents + countries) together by using the flatMap operator and leveraging the forkJoin operator to execute multiple API calls (countries) concurrently.

pegPaises2(): void {
  // Storing the continent response for later use within the subscribe function
  let continentResponse; 

  this.http.get('http://www.geonames.org/childrenJSON?geonameId=6295630')
    .flatMap((resContinents: Response) => {
        continentResponse = resContinents.json();
        // Generating an array of country APIs to be called in parallel
        let countryObservables = continentResponse.geonames.map(element => {
          return this.http.get(`http://www.geonames.org/childrenJSON?geonameId=${element.geonameId}`);
        });
        // Using forkJoin to make concurrent API calls
        return Observable.forkJoin(...countryObservables);
    })
    .subscribe(res => {
      // res contains an array of API responses
      // [country0Response, country1Response, country2Response, etc]
      // Utilize continentResponse + res to construct a continent-country object
    });
}

This is how the process unfolds:

  1. The continent API call is initiated.

  2. Based on the continent response, determine which country APIs need to be called simultaneously.

  3. Country APIs are executed concurrently.

  4. Upon completion of all country APIs, compile the data for continents and countries.

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 most effective way to transform values into different values using TypeScript?

If I have a list of country codes and I want to display the corresponding country names in my component, how can I achieve this using props? interface MyComponentProps { countryCode: 'en' | 'de' | 'fr'; } const MyComponent: ...

Angular: Extracting a String from an Observable of any Data Type

Currently, I have a backend REST service that is responsible for returning a string: @GetMapping("/role/{id}") public String findRole (@PathVariable("id") String username) { User user = userRepository.findByUsername(username); return user.getR ...

Updating DynamoDB objects seamlessly in Lambda functions without any conflicts

I am currently working with example Objects that follow this interface structure: interface Car{ id: Number; name: String; tires: Wheel[] } interface Wheel{ id: Number; name: String; radius: Number; } My goal is to store these Car Objects in DynamoDB and ...

Is time-based revalidation in NextJS factored into Vercel's build execution time?

Currently overseeing the staging environment of a substantial project comprising over 50 dynamic pages. These pages undergo time-based revalidation every 5 minutes on Vercel's complimentary tier. In addition, I am tasked with importing data for numer ...

Incorporating TypeScript into a project that already contains .js files

I currently have a NodeJS project with .js files written in ES6. I am interested in integrating typescript into this existing project. What steps should I follow? Can I simply introduce .ts files within the same directory structure? One issue I have encou ...

Only one choice for discriminated unions in react props

Looking to create a typescript type for react component props, specifically a basic button that can accept either an icon prop or a text prop, but not both. My initial attempt with a discriminated union didn't quite produce the desired outcome: inter ...

Tips for submitting a form with AngularJS version 4

I am developing a single page application using AngularJS 4. Can anyone guide me on how to submit a form upon clicking the submit button in AngularJS 4? Your help is greatly appreciated. Thank you! ...

Following the recent update to IntelliJ IDEA 2022.1.3, the use of ::ng-deep has been marked

After updating the version of IntelliJ, I noticed that the ::ng-deep angular material selector is now marked as deprecated. Here's an example: <mat-form-field class="register-custom-select"> <mat-select formControlName="gende ...

Controlling animation keyframes in Angular 2: a guide

Is there a way to manipulate CSS3/angular 2 animations using variables? Take a look at this modified code snippet from the official angular 2 animation docs: animations: [ trigger('flyInOut', [ state('in', style({position: &apos ...

Ensure Jest returns the accurate file paths for images in a TypeScript and React environment

I'm currently developing a React application and I have come across an issue with importing images. My usual method of importing images is as follows: import image1Src from 'assets/img1.png"; For testing purposes, I need to be able to make ...

Using Angular: filtering data streams from a date range observable object

I have a piece of code that seems to be functioning correctly, but I can't shake the feeling that it might just be working by chance due to an undocumented feature. I'm torn between questioning its validity or accepting that it is indeed designed ...

No output when using Typescript 2.0

Recently, I've been working on a project in VS 2015 update 3 and just integrated Typescript 2.0. Initially, I encountered a lot of errors and had to go through a trial and error process to resolve them. Now, all the errors have been fixed but I' ...

Using Angular to make an API call within a JavaScript function

I am facing an issue when trying to call an API in a JavaScript function as shown below. The injected services (subService) and defined variables (formData) are not recognized in the JavaScript function, resulting in an error of undefined addSub. How can I ...

Developing a barrel component in React (utilizing .tsx)

My current directory structure looks like this: src assets components models counter.tsx index.ts The code found inside models/index.ts (also known as the barrel file) export * from "./counter"; The code within models/counter.ts export default in ...

Facing a continuous issue where the Angular Universal Bundle keeps loading but only displays a

As I attempted to convert a basic Angular application into a universally supported application, I made all the necessary changes such as adding checks on DOM elements like window, navigator, setTimeout, etc. After running the command npm run build:ssr &am ...

Top method for transforming an array into an object

What is the optimal method for transforming the following array using JavaScript: const items = [ { name: "Leon", url: "../poeple" }, { name: "Bmw", url: "../car" } ]; into this object structure: const result = ...

Guidelines on incorporating emotion/styled into React applications with TypeScript

Including my root component in the ThemeProvider from @emotion/react has granted me access to props.theme. Here is an example: const StyledDiv = styled.div` background-color: ${(props) => props.theme.palette.primary.main}; `; Issue: TypeScript indica ...

Utilizing two DTOs for a single controller in NestJS

I'm having trouble retrieving and transforming different types of dtos from the body. My goal is to extract and transform firstDto if it's incoming, or convert secondDto if that's what's being received. However, my current code isn&apos ...

What steps can be taken to resolve the issue of being unable to rename an element in Typescript?

Why does VS code editor sometimes prevent me from renaming my typescript symbol using the f2 key? I keep encountering the error message "This element cannot be renamed." https://i.stack.imgur.com/mmqu9.png In some of my other projects, I am able to renam ...

The full-screen material dialog's Y-scrollbar is overlapping with the page's Y-scrollbar

I'm currently working on a material dialog that takes up the full screen. The content of the dialog is larger than the screen height, resulting in a vertical scrollbar within the dialog. However, the overall page is also taller than the screen height ...