[SOLVED] Why does the service return me undefined when I request an item in Angular?


I have a service in Angular that returns an array of Any types

import { Injectable } from '@angular/core';
import axios from "axios";

  providedIn: 'root'

export class BooksService {

  private books:any[] = [];

  constructor() {
    this.books = this.getData()

      .then(data => {
          return data;
      .catch(error => {
          return error; 

    return this.books;

    return this.books[idx]

so when in my component I call the ‘getBooks’ function I get the following

enter image description here

which works fine, but when I call the ‘getBook()’ function


It returns ‘undefined’, does anyone know why?

enter image description here


I think it’s because the console.log function is not ‘waiting’ for the get request to get through. You should call the getBook function on the constructor, or anyways before calling console.log.

Answered By – Catalina Zecchin

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *