What is the process for retrieving information from an observable array?

I am currently developing an application with a Python backend and Angular frontend. The main functionality of the app involves retrieving FIFA players from a MongoDB using the getLoyalPlayers function.

Below is the snippet from the loyalty.component.ts file:

import { Component } from "@angular/core";
import { WebService } from './web.service';

@Component({
  selector: 'loyal',
  templateUrl: './loyal.component.html',
  styleUrls: ['./loyal.component.css']
})
export class LoyalComponent {
  constructor(public webService: WebService) {}

  ngOnInit() {
    this.player_list = this.webService.getLoyalPlayers();
  }

  player_list: any = [];
}

This is the section from web.service.ts:

  getLoyalPlayers(loyalPage: number) {
    return this.http.get('http://localhost:5000/api/v1.0/loyal-players');
  }

The retrieved data is then rendered in loyalty.component.html using async:

<div *ngFor="let player of player_list | async">
    <!-- Individual items can be accessed like -->
    {{ player.short_name }}
</div>

In trying to access the elements within this array in the typescript file, I attempted the following approach:

ngOnInit() {
    if (sessionStorage['loyalPage']) {
      this.page = Number(sessionStorage['loyalPage']);
    }

    this.player_list = this.webService.getLoyalPlayers(this.page);

    console.log(this.player_list.short_name)
}

However, this resulted in a value of undefined:

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

I am seeking guidance on how to properly retrieve this data. How should I proceed?

Answer №1

When dealing with observables, there are three different approaches to consider:

  1. Utilize the pipe async method (indicated by |async in .html).
  2. Subscribe to the observable, save the result in a variable, and loop through that variable. Remember that the variable only holds a value after the call is complete.
    this.apiService.getData(this.page).subscribe((response:any)=>{
        this.data=response;  //<--note that data is the "object" here
        //you can now use 
        console.log(this.data)
     })
      //but you cannot use it here
        console.log(this.data)
  1. Use tap within the pipe operator to store the value in a variable. Tap is executed after the observable has been subscribed to and completed - pipe async enables this functionality.
    //observe that this.data$ is an Observable
    //in Angular, the "$" conventionally signifies an observable
    this.data$=this.apiService.getData(this.page)
       .pipe(tap((response:any)=>{
        this.data=response;
        //now you can use 
        console.log(this.data)
     }))

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

Exploring Angular: distinguishing between sessions on separate tabs

I am currently working on a web application that utilizes Angular for the front end and a Django Rest API for the back-end. In some cases, I need the Django Rest API to be able to distinguish between polling requests using session IDs. After conducting som ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18. Below is the code snippet I am currently working with: <form [formGroup]="form"> ...

Error encountered: ExpressionChangedAfterItHasBeenCheckedError when trying to load the loading indicator

I encountered an issue with my loading indicator that I cannot seem to resolve: LoadingIndicatorComponent.html:2 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'hidden: true&ap ...

A step-by-step guide on dynamically binding an array to a column in an ag

I am currently working with the ag-grid component and I need to bind a single column in a vertical format. Let's say I have an array ["0.1", "0.4", "cn", "abc"] that I want to display in the ag-grid component as shown below, without using any rowData. ...

The Angular application is encountering difficulty accessing the Django Rest Framework API due to a CORS problem

Encountering a CORS problem while trying to access a Django Rest Framework REST API from an Angular 6 application. The API is hosted at http://localhost:55098/admin. It functions properly when accessed with Insomnia. The Angular app is running on http://l ...

Guide to incorporating d.ts file for enhancing intellisense in VS Code using a method akin to the NPM approach

In my nodejs project (in JS), I find myself relying heavily on node global variables. Despite receiving warnings against using globals, everything works well except for one thing: The lack of intellisense for globals. Every time I need to use a global fu ...

Oops! The program encountered an issue on the production environment, but it's running smoothly

When I execute Webpack using the command node node_modules/webpack/bin/webpack. js --env. prod An error message is displayed below. However, when running in --env. dev mode, the command executes without any issues. Can't resolve './../$$_gen ...

Tips on customizing Char.js doughnut charts

How can I make the doughnut thinner while keeping it thicker? What adjustments should be made? I attempted to implement changes and it worked successfully, but now I need to adjust the width. How can I do this? TS File. import { Component, OnInit } from ...

Accessing the property of an object with TypeScript

I am working with an array of objects, where each object contains two properties: {key:count} When configuring my chart, I need to set the data source in this format: {meta: "unknown", value: [the count of unknown]}, {meta: "male", value: [the count of ...

Utilizing TypeScript 2's Absolute Module Paths

The issue at hand: I am facing a challenge with relative module paths and have attempted to resolve it by configuring the baseUrl setting in my tsconfig.json file. Despite my efforts, I keep receiving an error indicating that the module cannot be found. I ...

What is the method to access an interface or type alias that has not been explicitly exported in TypeScript type definitions?

I am looking to create a new class that inherits from Vinyl. The constructor in the superclass takes a single parameter of type ConstructorOptions. export default class MarkupVinylFile extends Vinyl { public constructor(options: ConstructorOptions) { ...

Encountered an issue launching the advanced web server and reverse proxy server nginx for high performance

UPDATE - Recently, I encountered the following error logs: nginx: [emerg] unknown "request_url" variable Aug 19 01:14:58 nginx[4890]: nginx: configuration file /etc/nginx/nginx.conf test failed Below is my nginx.conf file: user www-data; worker ...

Creating a tsconfig.json file that aligns perfectly with your package.json and tsc command: a step-by-step

I've chosen to use TodoMvc Typescript-Angular as the starting point for my AngularJS project. Everything is working smoothly so far. Here's a breakdown of what I can do: To manage all dependencies, I simply run npm install or npm update based o ...

Creating an app for sending text messages and making video calls with Spring Boot technology

I am interested in developing an application with Spring Boot that allows users to make video calls and share text messages. I also want the ability to save these videos for future viewing by registered users of the app. Although I am familiar with node.j ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

Click event based on condition in Angular 2

Is it possible to implement a conditional click event in my application? <div class="trashIconDiv" (click)="if(idx > 0) {removeSelected(item.spId)}"> In the code snippet above, the removeSelected function is supposed to execute only when idx is ...

Utilize JQuery to choose the angular element

Can Angular tags be selected using JQuery? I am currently utilizing the ui-select Angular component, which is integrated into the HTML page as shown below: <ui-select ng-model="rec.currencyCode" on-select="ctrl.selectCurrencyCode(rec, $item)"> & ...

What improvements can I implement in this React Component to enhance its efficiency?

Seeking advice on improving the efficiency of this React Component. I suspect there is code repetition in the onIncrement function that could be refactored for better optimization. Note that the maxValue prop is optional. ButtonStepper.tsx: // Definition ...

"Uploading user profile images with Angular, Express, Multer, and Mongoose made easy

Hey there, I'm currently using multer to upload images. When I select an image, it gets saved in the backend folder called uploads. However, I would like to store it in a MongoDB database and then display that image on the frontend using Angular. I&ap ...