Retrieving data from an Array

I've encountered a peculiar issue while working on a test project. It seems that I am unable to access values in an array.

pokemonStats$: Observable<PokemonStats[]>;

getPokemonStats(id: number): any {
this.pokemonStats$
.pipe(take(1))
.subscribe(stats => {
  console.log(stats instanceof Array);
  console.log('length', stats.length);
  console.log('du', stats);
  console.log('test', stats[1]);
});
}

Here is the unexpected output:

https://i.sstatic.net/ObOKW.png

I'm puzzled by this behavior. A colleague has suggested that it might be an array-like structure, which prompted me to add the 'instanceof' log. Any assistance would be greatly appreciated.

EDIT: Here is the code where the array is populated.

this.pokemonStats$ = this.getAllPokemonStats(ids);

getAllPokemonStats(ids: number[]): Observable<PokemonStats[]> {
const pokemonArray: PokemonStats[] = [];
ids.forEach(id => {
  const url = 'https://pokeapi.co/api/v2/pokemon/' + id;
  this.http.get(url)
    .pipe(take(1))
    .subscribe((data: PokemonStatsAPI) => {
      pokemonArray.push({
          id: data.id,
          name: data.name,
          speed: data.stats[0].base_stat,
          hp: data.stats[5].base_stat,
          attack: data.stats[4].base_stat,
          defense: data.stats[3].base_stat
        });
    });
});
return of(pokemonArray);

}

Answer №1

The approach you're taking involves returning the new observable with the pokemonArray, which starts empty and will be filled asynchronously. This results in it being empty when subscribing to getAllPokemonStats.

To resolve this issue, consider using the forkJoin operator for performing the http requests and then mapping them using the map operator:

getAllPokemonData(ids: number[]): Observable<PokemonData[]> {
  return forkJoin(
    ids.map(id => {
      return this.http.get(`https://pokeapi.co/api/v2/pokemon/${id}`);
    })
  ).pipe(
    map(results => results.map(data => ({
      id: data.id,
      name: data.name,
      speed: data.stats[0].base_stat,
      hp: data.stats[5].base_stat,
      attack: data.stats[4].base_stat,
      defense: data.stats[3].base_stat
    })),
  );
}

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

Tips for merging two tables without duplicate entries

I require assistance with the following task, I am looking to write the code for this Array ( [0] => 1 [duration] => 1 [1] => Singapore [ai_Name] => Singapore ) {"duration":"1","ai_Name":"Singapore"} however, the output I am receiving is ...

Encountering an i18next-fetch-backend issue during the transition to Angular 11

https://i.sstatic.net/TwrBx.png Encountering problems after upgrading to Angular 11 with the i18next-fetch-backend package's index.d.ts file. How can I troubleshoot this issue and what steps should I take to resolve it? Here is a snippet from the in ...

Angular Router navigation not functioning as expected

I have successfully implemented routing in my Angular project. Below are the routes defined in the root module: const appRoutes: Routes = [ { path: '', component: LoginComponent }, { path: 'dashboard', canActivate: [AuthGuard], comp ...

Having trouble adding @angular/fire to my Angular project

Having trouble adding Firebase authentication to my Angular project, specifically when running npm install @angular/fire. I keep encountering the following error: > npm ERR! code ERESOLVE > npm ERR! ERESOLVE unable to resolve dependency tree > ...

GraphQL Error: Invalid syntax - expecting a Name but found $

Facing an issue with updating data in GraphQL (Angular Apollo) as I receive the error message GraphQLError: Syntax Error: Expected Name, found "$" This is what I am doing: const CONFIRM_CITA = gql` { mutation changeConfirmationStatus ($cen ...

Explore the use of enumerations within a class

My code structure includes: position.utils.ts enum PositionDirectionEnum { LEFT, RIGHT, TOP, BOTTOM, AUTO } export class PositionUtil { public static PositionDirection: PositionDirectionEnum } utils.ts import { PositionUtil } from "./position. ...

Looking for a way to style the user's selection in a Ng Bootstrap typeahead component without using resultFormatter?

I have implemented a ngBootstrap typeahead for selecting a person from a list of results. Each result, which is an object retrieved from an API, is displayed as Name + ID in the list by using the resultFormatter input. However, after clicking on a result, ...

Scrollable Turbo Table experiencing a problem with the PrimeNG filter dropdown

When using PrimeNG Turbo Table, I am facing an issue where the filter dropdown is getting placed inside the scrollable table. The dropdown works perfectly fine without the scrollable table. You can see it in action here. However, when the table is scroll ...

What is the method for inserting an object into a jsonArray in TypeScript?

I am trying to add an object to existing JSON data in TypeScript. I am new to TypeScript and have created an array variable called jsonArrayObject, which contains a boolean[] type. This jsonArrayObject holds a contactModel object with properties like fname ...

"Attempting to access a Service in Angular before it has been initialized is

When I try to run tests, they fail right at the beginning with an error message: Chrome 83.0.4103.61 (Linux x86_64) ERROR An error was thrown in afterAll Uncaught ReferenceError: Cannot access 'SomeService' before initialization ReferenceE ...

Deciphering elements within an array using Node.js

After receiving a JSON code from a database, I am faced with the challenge of parsing an object within an array. The specific structure of the code is proving to be a hurdle in my efforts. [ { name: 'John1', surname: 'Doe1' }, { name ...

Leverage TypeScript AngularJS directive's controller as well as other inherited controllers within the directive's link function

I am currently developing an AngularJS directive in TypeScript for form validation. I am trying to understand how to utilize the directive's controller and inherit the form controller within the directive's link function. Thank you in advance! ...

Troubleshooting the Issue with Angular Material Dialog Imports

Hey there, I'm trying to utilize the Angular Material dialog, but I'm encountering issues with the imports and I can't seem to figure out what's wrong. I have an Angular Material module where I imported MatDialog, and I made sure to i ...

Attempting to launch Angular application on GitHub Pages

I need help deploying my Angular application on GitHub pages using node.js 14.20.0. I've successfully installed: npm i angular-cli-ghpages However, when I try to run : ng deploy --base-href=https://rejkid.com.github.io/ScheduleMeFrontEnd/ as recomme ...

What is the best way to store query responses in global.arrays without overwriting the existing values stored within the array elements of global.arrays?

QUESTION: I am struggling to efficiently assign results of MongoDB queries to global arrays. I attempted to store references to the global arrays in an array so that I could easily assign query results to all of them using a for loop. However, this appro ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clic ...

Angular2 - Issue with Pagination functionality

When incorporating ng2-bootstrap as a pagination component, the guide provided at () made setting up the component a breeze for me. The pagination functionality is working smoothly and meeting my expectations. However, I've encountered an issue when ...

I am attempting to iterate through a multidimensional array using a foreach loop

$details = array( array( 'name' => 'Ahmed', 'age' => 24, 'hobbies' => array('swimming','Drawing','Programming') ) ); The desired final re ...

displaying an item within a text field

I have an input box created using Angular reactive forms <input type="text" formControlName="OrgName" placeholder="Enter name" maxlength="60"> <p class="fieldRequired" *ngIf="showNameMSg" ...