Encountering a bug in Angular 11 while fetching data from the backend to display on the screen - facing an issue with trying to access property 'values' of an undefined variable

I am currently working on retrieving data from the backend/api and attempting to display it using *ngFor. However, I am encountering the following errors:

Cannot read property 'values' of undefined

Below are the components, service codes, and authorization method in contas.component:

import { Component, OnInit } from '@angular/core';
import { NgbModal, ModalCloseReasons } from '@ng-bootstrap/ng-bootstrap';
import { ContaBancaria } from 'src/app/models/conta-bancaria';
import { ContaBancariaService } from './services/contas.service';

@Component({
  selector: 'app-contas',
  templateUrl:'./contas.component.html'
})
export class ContasComponent implements OnInit {
  closeResult = '';

  public contasBancarias: ContaBancaria[];
  errorMessage: string;

  constructor(private modalService: NgbModal,private contaBancariaService: ContaBancariaService) {}


  ngOnInit(): void{
    this.contaBancariaService.obterTodos()
      .subscribe(
        contasBancarias => this.contasBancarias = contasBancarias,
        error => this.errorMessage);
        console.log(this.contasBancarias.values);
  }

}

Next is the code snippet from contas.service:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

import { Observable } from "rxjs";
import { catchError, map } from "rxjs/operators";

import { BaseService } from 'src/app/services/base.service';
import { ContaBancaria } from '../../../../models/conta-bancaria';

@Injectable()
export class ContaBancariaService extends BaseService {

    contaBancaria: ContaBancaria = new ContaBancaria();

    constructor(private http: HttpClient) { super() }

    obterTodos(): Observable<ContaBancaria[]> {
        return this.http
            .get<ContaBancaria[]>(this.apiUrlRestrita + "/contasbancarias", super.ObterAuthHeaderJson())
            .pipe(
                catchError(super.serviceError));
                
    }
}
protected ObterAuthHeaderJson() {
        return {
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.LocalStorage.obterTokenUsuario()}`
            })
        };
    }

EDIT: Here is the expected JSON/data format from the API for reference:

Answer №1

If you're looking for a solution, I suggest giving this a shot.

this.bankAccountService.getAll()
      .subscribe(
        bankAccounts => {this.bankAccounts = bankAccounts
 console.log(this.bankAccounts ? this.bankAccounts.values: "not found");
},
        error => this.errorMessage);
       
  }

When making an API call and trying to display the data afterwards, keep in mind that the console statement may run first due to the time it takes for the API call to complete.

Answer №2

I managed to figure it out by adjusting the subscribe method to this:

 ngOnInit(): void{
    this.bankAccountService.getAll()
      .subscribe(
        (v) => {
          this.bankAccounts = v["data"]
          console.log(this.bankAccounts)
        } 
      )
  }

Grateful for everyone's assistance! <3

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

Step-by-step guide to creating a custom wrapper in React that modifies the props for a component

Exploring React components for the first time and seeking assistance. I am interested in dynamically wrapping one component inside another and modifying its props. For instance, considering the following component: If we want to pass the key3 from a wrapp ...

Avoid the import of @types definition without exports in TypeScript to prevent the error TS2306 (not a module)

I have spent a considerable amount of time trying to load a NodeJS library that has what I believe is a faulty type definition in the @types repository. The library in question is geolib and its types can be found in @types/geolib Although I am aware tha ...

What sets apart using (@Inject(Http) http: Http) from not using it?

Following a recent query, I now have a new question. What sets apart these two approaches? Here is the original code I used: import {Http, HTTP_PROVIDERS} from 'angular2/http'; @Component({ viewProviders: [HTTP_PROVIDERS], ..// constructor(h ...

Component declaration in Typescript is being rejected due to the union type not being accepted

In my current project, I'm working on a component that should accept either an onClick or a to prop. const StickyButton: React.FC< ({ onClick: MouseEventHandler } | { to: string }) & { buttonComponent?: ({ onClick: MouseEventHandler }) =& ...

Error in JavaScript: A surprise anonymous System.register call occurred

Within Visual Studio 2015, there exists a TypeScript project featuring two distinct TypeScript files: foo.ts export class Foo { bar(): string { return "hello"; } } app.ts /// <reference path="foo.ts"/> import {Foo} from './f ...

The plugin by chartjs-plugin-crosshair is malfunctioning

Having some trouble with the chartjs-plugin-crosshair - it's not working as expected. Here are the packages I am using: "chart.js": "^3.9.1" "chartjs-plugin-crosshair": "^1.2.0" Seems like there might be an i ...

How to prevent duplicate database entries in Angular forms?

Currently, I am working on a project using Angular and TypeScript. The goal is to retrieve a list of users from an API and allow for the addition of new users. However, I am struggling with determining how to verify if a user with a specific name already e ...

Matching the appropriate data type for interface attributes

In the process of developing a module (module1), I have defined the following interface type: interface ModuleOneInterface { keyOne: customInterface; keyTwo: customInterface; keyThree: customInterface; } Now, as I work on another module (modul ...

Guide on toggling the button by clicking on the icon to turn it on or off

Within my angular application, I have implemented font icons alongside a toggle switch. Initially, the switch is in the ON state. The specific functionality desired is for clicking on an icon to change its color from white to red (this has been achieved) ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

Using TypeScript to utilize an enum that has been declared in a separate file

Imagine I have defined an enum in one file (test1.ts): export enum Colors{ red=1, blue=2, green=3 } Then in another file (test2.ts), I am creating a class with a method. One of the parameters for that method is a Color from the Colors enum: ...

What could be the reason why the keypress event doesn't seem to be functioning properly on

Currently, I am utilizing Angular and the Ionic framework. Here is a snippet of the HTML code that I have written: <div><ion-input type="text" id="phoneNumber" [(ngModel)]="phoneNumber" (keypress)="phoneNumericCh ...

Obtain the outcome of HTML5 FileReader by utilizing promises within an asynchronous function

I am encountering a challenge in my Angular 4 application where I am working with an image. I am trying to pass the base64 string to another variable, but due to the asynchronous nature of this process, the image.src ends up being empty. As a result, the ...

Required Peer Dependency Not Satisfied: [email protected] is requesting @angular/[email protected]

DETECTED Missing Dependency: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5525393421333a27387837273a2226302778312c3b34383c3615617b667b60">[email protected]</a> requires @angular/<a href="/cdn-cgi/l/email-prot ...

Adding ngrx action class to reducer registration

Looking to transition my ngrx actions from createAction to a class-based approach, but encountering an error in the declaration of the action within the associated reducer: export enum ActionTypes { LOAD_PRODUCTS_FROM_API = '[Products] Load Products ...

Converting hierarchical JSON data into a table with rowspan using Angular

I am facing a challenge in creating a table using nested JSON obtained from an API. I am unsure how to dynamically merge cells when needed, especially since the JSON structure can be nested up to 6 or 7 levels. Desired Table : Expected Table Current Ou ...

Adding a local image to Firebase Storage in Angular5 / Ionic3

Uploading images is a breeze using the following method (select input file): import { AngularFireStorage } from 'angularfire2/storage'; @Component({ selector: 'app-root', template: '<div>' + '<input c ...

Updating non-data properties dynamically in a custom AG Grid cell renderer

In my grid setup, I have implemented an editor button in a column for each row and a new item creator button outside the grid. One of the requirements is that all buttons should be disabled when either the create or edit button is clicked. To achieve thi ...

Encountered difficulty locating the module path 'stream/promises'

When importing the following in a typescript nodejs app import { pipeline } from "stream/promises"; Visual Studio Code (vscode) / eslint is showing an error message Unable to resolve path to module 'stream/promises' https://i.sstatic. ...

Unexpected blank space detected at the bottom of the page in Angular 13

Using the NGX-ADMIN template built on Angular 12 has been smooth sailing until an upgrade to Angular 13. With this simple version change, I am now faced with a perplexing issue that I can't seem to pinpoint or resolve. I can confidently say that shif ...