I'm having trouble retrieving the information as it is showing as undefined. Can anyone offer any advice?

Attempting to extract specific information from an API response has proven challenging. Despite my efforts to isolate the desired data, all listed details appear as undefined.

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AnyArray } from 'mongoose';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  fetchCountryData (country: string) {
    let formattedCountry = country.split('-').join(' ');
    let api1 = `http://api.worldbank.org/v2/country/${formattedCountry}?format=json`;
    let api2 = ``
    return this.http.get(api1)
  }

  setCountryData(country: string) {
    let subject = new Subject();

    this.fetchCountryData(country).subscribe((data: any) => {
       subject.next({
        country: data.name,
        capital: data.capitalCity,
        income: data.incomeLevel,
        region: data.adminregion,
        latitude: data.latitude,
        longitude: data.longitude,
       }) 
    })

    return subject.asObservable();
  }
}

The API response contains:

(2) [{…}, Array(1)]
0
: 
{page: 1, pages: 1, per_page: '50', total: 1}
1
: 
Array(1)
0
: 
adminregion
: 
{id: 'EAP', iso2code: '4E', value: 'East Asia & Pacific (excluding high income)'}
capitalCity
: 
"Beijing"
id
: 
"CHN"
incomeLevel
: 
{id: 'UMC', iso2code: 'XT', value: 'Upper middle income'}
iso2Code
: 
"CN"
latitude
: 
"40.0495"
lendingType
: 
{id: 'IBD', iso2code: 'XF', value: 'IBRD'}
longitude
: 
"116.286"
name
: 
"China"
region
: 
{id: 'EAS', iso2code: 'Z4', value: 'East Asia & Pacific'}
[[Prototype]]
: 
Object

Struggling with errors in specifying the array format due to integer labels. Seeking assistance for resolving this issue.

Answer №1

After some trial and error, I finally cracked the code. My initial attempts with data.name, data[1].name, and data[0].name didn't yield the desired results. However, I found success with data[1][0].name.

It seems that the key to unlocking the correct value lies in navigating through nested arrays within the data structure.

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

Obtaining undefined values for req and resolvedUrl in GetServerSideProps function

In my project, I am currently using next.js version ""next": "^12.1.4"" and node version ""@types/node": "^14.14.6". I have created a function called getServerSideProps with parameters req and resolvedUrl. When the ...

Show various perspectives depending on the circumstances

I am looking for a solution to display a different component if my ngFor loop returns null. <ion-select interface="popover" [ngModel]="selectedKidId"> <ion-option *ngFor="let kid of kids" [value]="kid.id">{{kid.name}}</ion-option& ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

Issue encountered when attempting to display JSON index on individual result page

This is a JSON response. { "listing": { "id": "1", "name": "Institute Name", "contact": "9876543210", "website": "http://www.domain.in", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

The form submission is yielding an incorrect value

When creating multiple form groups, the issue arises where submitting one form returns the value of the last entered form. export class ExpansionOverviewExample { panelOpenState = false; tables: string[] = ['one', 'two', 'three ...

Trouble with Angular 7: Form field not displaying touched status

I am encountering an issue while trying to input data into a form, as it is not registering the touched status. Consequently, an error always occurs when attempting to send a message back to the user. In my TypeScript file, I am utilizing FormBuilder to c ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

The Typescript hello world example encounters an issue with Karma

Recently, I encountered an issue while working on a TypeScript project with Jasmine and Karma. It seems that Karma is unable to execute the compiled unit tests due to an error showing up in Chrome: Uncaught ReferenceError: define is not defined To illust ...

What is causing the consistent occurrences of receiving false in Angular?

findUser(id:number):boolean{ var bool :boolean =false this.companyService.query().subscribe((result)=>{ for (let i = 0; i < result.json.length; i++) { try { if( id == result.json[i].user.id) ...

Setting a background image in vanilla-extract/css is a straightforward process that can instantly enhance

I am brand new to using vanilla-extract/CSS and I have a rather straightforward question. I am attempting to apply a background image to the body of my HTML using vanilla-extract, but I am encountering issues as I keep getting a "failed to compile" error. ...

Issue with the functionality of the material tree's parent node may not be operating

I created a material tree with the ability to select up to 42 elements. Once the limit is reached, the nodes become disabled. However, I encountered an issue where if some child nodes are selected while others are disabled due to reaching the limit, the pa ...

Discover the power of working with asynchronous values in objects using the latest @if syntax in Angular 17

Previously, we were able to chain multiple async operations using *ngIf directives in Angular. This allowed us to avoid repeating the async pipe in the template and instead reuse them as a single subscription. With the introduction of the new @if syntax in ...

Error in Typescript for a function that accepts several types of lists - property does not exist on the interface

In my project, I have defined three interfaces: a base interface and two others that extend the base one with children as properties. One of the interfaces includes 'valueType' while the other includes 'returnType'. Here is how they are ...

Encountering a 404 error with Angular 6 routing after refreshing the page when using an Nginx proxy

I currently have my angular application running within a docker container, exposed on port 83. Additionally, I have a separate spring-boot rest app running inside another docker container, exposed on port 8083. On the host server, there is an Nginx server ...

How can we design a return type for a function in Typescript that enforces the exact keys present in the input array K[] to be included in the Record?

I have a function that takes an array of Animals, and returns a map where the keys are the animals and the values are their fur colors: export enum Animals { CAT = 'CAT', DOG = 'DOG', SEAL_PUP = 'SEAL_PUP', } const furC ...

Is it possible for Angular's ngStyle to accept multiple functions? If not, what is the alternative solution?

Can multiple conditions be added to different attributes with ngStyle? Is it possible to change text color and background color based on specific JSON values using ngStyle? About the Project: I am currently working on creating a tab bar that resembles a ...

Personalized angular subscription malfunction

Recently, as I dive into learning Angular 6, a question has arisen regarding the subscribe method and error handling. A typical use of the subscribe function on an observable typically appears like this: this.myService.myFunction(this.myArg).subscribe( ...

Ways to include x-api-key in Angular API request headers

I am attempting to include the x-api-key header in the headers, as shown below: service.ts import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { Observable } from ...

Encountering a unique webpack error while attempting to upgrade Angular from version 11 to version

Struggling to upgrade my Angular version from 11.1.1 to 12.1.1 and encountering a build error. "CustomWebpackDevServerSchema" schema is using the keyword "id" which its support is deprecated. Use "$id" for schema ID. "BuildCustomWebpackBrowserSchema" sche ...

What is the function of the Angular dependency injection mechanism?

I'm trying to grasp the inner workings of Angular/NestJs dependency injection. It's intriguing how the type of parameters gets lost when a Typescript class is constructed. For example: type Dependency1 = {}; type Dependency2 = {}; class X { ...