Angular is giving me an undefined Array, even though I clearly defined it beforehand

I've been working on integrating the Google Books API into my project. Initially, I set up the interfaces successfully and then created a method that would return an Array with a list of Books.


    public getBooks(): Observable<Book[]>{
        return this.http.get<Book[]>('https://www.googleapis.com/books/v1/volumes?q=filibusterismo');
    
      }

(I specified the search term as "filibusterismo" to avoid mistakes, but planned to change it later.)

Now, the challenge is using the Array of Book in my application. The issue arises because the getBooks method returns an observable Array of Books instead of a regular Array. Here is how I initially attempted to handle it:


   books:Book[];
     constructor(private GoodreadsService:GoodreadsService) { }
   
     ngOnInit() {
      this.libro=this.GoodreadsService.getBooks();
   }

I tried to resolve this by utilizing async:

*ngFor="let book of books | async"

However, I encountered the same problem. After doing some research on Stack Overflow, I learned that I need to use subscribe in the ngOnInit() function, like so:


     this.GoodreadsService.getBooks().subscribe(res=>{this.books=res},
          error => { // on failure
            console.log('Error Occurred:');
          });

The issue persists as even though there are no apparent errors being returned, when I try to log

console.log(this.libro1);

The console indicates that the array is undefined, despite being defined as an array of Book. Additionally, I am still unable to utilize ngFor loop.

I also attempted to map the getBook method to return a regular Array instead of an observable array, but was unsuccessful despite researching numerous related questions on Stack Overflow.

If anyone can provide insight on how to resolve this issue and enable me to effectively use an ngFor loop in the HTML code, I would greatly appreciate it.

Here is a snippet of my HTML:


    <p>busqueda works!ss </p>
    <table>
      <thead>
          <th>Name</th>
          <th>Indexs</th>
      </thead>
      <tbody>
        <div *ngFor="let book of books | async">
            <h1  >
                <p>prueba</p>
            </h1>
          </div>
      </tbody>
    </table>

Answer №1

Follow these steps to successfully complete the task. Begin by initializing the API call and subscribing to it in order to send the request. Once the response is received, iterate through the items.

For a functional example, please check out the provided stackblitz here.

Sample component.ts :

import { Component, OnInit } from "@angular/core";
import { SampleService } from "./sample.service";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  books: any;
  constructor(public sample: SampleService) {}
  ngOnInit() {
    this.sample.getBooks().subscribe(data => {
      console.log(data.items)
      this.books = data.items;
    });
  }
}

Sample HTML :

<table>
    <thead>
    </thead>
    <tbody>
        <div *ngFor="let book of books">
            <h4>
                <p>kind : {{book.kind}}</p>
        <p>Id : {{book.id}}</p>
        <p>etag : {{book.etag}}</p>
            </h4>
        </div>
    </tbody>
</table>

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

Is there a way to dynamically change the options in a dropdown menu using Angular?

I am facing an issue where the values in my dropdown list are changing to null when I click on the form. The add function is working correctly, but this update problem is bothering me. Can anyone provide assistance? Below is the snippet of my HTML code: ...

What is the best method for incorporating an Angular Component within a CSS grid layout?

I recently started learning Angular and am currently working on a project that requires the use of a CSS grid layout. However, I'm facing an issue with inserting a component inside a grid area specified by grid-area. My attempt to achieve this in app ...

Ultimate combo: React, TypeScript, and Vite for seamless imports!

Problem The issue I'm facing is related to my React app built with the command yarn create vite. I tried to switch to using absolute imports instead of "../../.." in my files, but unfortunately it doesn't seem to work in my React + Vi ...

What is the best way to bring in a SCSS file within another SCSS file?

When working with SCSS, I find myself using a lot of variables. To keep things organized, I create a separate file that contains all of my SCSS variables. The next step is to import this file into other SCSS files. Here's what I tried: Create a fil ...

The ace.edit function is unable to locate the #javascript-editor div within the mat-tab

Having trouble integrating an ace editor with Angular material Error: ace.edit cannot locate the div #javascript-editor You can view my code on StackBlitz (check console for errors) app.component.html <mat-tab-group> <mat-tab label="Edito ...

Error message displaying that the argument for the onChange state in a jhipster react form is not assignable as type '{ [x: number]: any; }'

Just diving into the world of React and encountering a bit of a struggle with jsx when it comes to setting state in a form that contains two fields and triggers an ajax call to store a json object (response data) in the state's field3. The code I curr ...

Leverage jsencrypt in Ionic 3

Struggling to hash passwords for login on my Ionic 3 app, I attempted using jsencrypt following a tutorial but encountered issues as I couldn't grasp how it works... Here's what I tried : npm install --save jsencrypt import { Component } from ...

ng-bootstrap component 404 error on final angular2 release

angular2 final release. ng-bootstrap alpha v.5 bootstrap components are functioning on html, however when attempting to import them like this import {ViewChild} from "@angular/core/src/metadata/di"; import {NgbDropdown} from "@ng-bootstrap/ng-bootstrap/d ...

Is it best practice to create a new component for each dialog modal pop-up in Angular?

Currently, I have developed an Angular component for a dialog window utilizing Angular Material. However, I now require another dialog modal. Should I consider creating a separate component for this new dialog? ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

When attempting to create a new page in Ionic 5, the error message "**An NgModule could not be located**" is being displayed

While attempting to create a page using ionic g page pages/first, I encountered the following error: Could not find an NgModule. Use the skip-import option to skip importing in NgModule. [ERROR] Could not generate page However, when I tried ionic g page s ...

Developing a custom package containing personally crafted type definitions and importing them into the project

I'm in need of creating a private npm package specifically for custom type definitions (typedefs) that are hand-written d.ts files not generated by TypeScript. Since these are proprietary, they cannot be added to DefinitelyTyped. The folder structure ...

React Query mutation encountered a TS2554 error: Type argument was not valid

I'm a beginner when it comes to TypeScript and I am using react-query. I tried using mutate, but it is causing an error. TS2554: Expected 1-2 arguments, but got 3. interface: interface ChangePassword{ email: string; password: string; conf ...

Encountering a problem while attempting to host an Angular application on localhost:4200

After executing the ng serve command, I encountered an issue in the browser: An error occurred while trying to resolve "localhost:4200" ("") for "10.238.0.0": rpc error: code = Unknown desc = no such record I apologize if this question seems basic, as I ...

Typescript - Specifying the return type for a deeply nested object

I have a container that holds multiple sub-containers, each containing key-value pairs where the value is a URL. I also have a function that takes the name of one of the sub-containers as input, loops through its entries, fetches data from the URLs, and re ...

Combining property values based on a common property in an array of objects using JavaScript

I have a large array filled with various objects structured like: [ { "type": "bananas", "count": 15 }, { "type": "kiwis", "count": 20 }, { "type": "bananas", ...

Unleashing the power of TypeScript with Solid JS Abstract Class

Why am I getting an undefined error for my calcUtilisation method when using an Abstract Class as the type in createStore? Is there a way to utilize a type for the data along with a method within the same class for createStore? abstract class Account { ...

Utilize a single Angular 5 deployment to connect with numerous clients

My plan is to utilize a single Angular 5 application instance for two distinct clients, identified as X and Y. The backend of my system is developed using Java, and it is designed in a way that all data interactions are determined by the client ID. In thi ...

How can I effectively build an Angular Library containing various components?

I am currently restructuring the core elements that form a search page into an angular library. My goal is to include various components in this angular library, such as SearchControls, PageHeader, PageFooter, and more. I intend to insert <search-contro ...

Typescript: How to Ensure Tuple Type is Explicit and Not Combined

I have a code snippet that defines a person object and a function to get its values: const person = { name: "abc", age: 123, isHere: true }; const getPersonValues = () => { return [person.name, person.age, person.isHere]; }; const [n ...