Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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";

@Injectable({
  providedIn: 'root'
})

export class BooksService {

  private books:any[] = [];

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

  getData()
  {
    axios.get(`https://localhost:3000/api/get`)
      .then(data => {
          return data;
      })
      .catch(error => {
          return error; 
      })
  }

  getBooks():any[]
  {
    return this.books;
  }

  getBook(idx:number):any
  {
    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

console.log(this._booksService.getBook(1))

It returns 'undefined', does anyone know why?

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda