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

346
Visualizações
API Data undefined when used in the component

i have this service to get data from the api and save it into arrays afterwards:

export class DataService {
constructor(private http: HttpClient) { }

readonly baseURL = "https://localhost:44302/api";
books: Book[];
users: User[];
cards: Card[];
postId: number;

httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

getBooks() {
  return this.http.get(this.baseURL + '/books');
}
getCards() {
  return this.http.get(this.baseURL + '/cards');
}
getUsers() {
  return this.http.get(this.baseURL + '/users');
} 
getData() {
  const observableList: Observable<any>[] = [];

  observableList.push(this.getBooks());
  observableList.push(this.getUsers());
  observableList.push(this.getCards());

  forkJoin(observableList).subscribe(resultList => {
    this.books = resultList[0] as Book[];
    this.users = resultList[1] as User[];
    this.cards = resultList[2] as Card[];
  });
}

in my component, i run the getData method and try to console.log the data but it keeps saying that the data is undefined, even though the api data shows up in the debugging-network tab:

export class MainComponent implements OnInit {
books: Book[];
users: User[];
cards: Card[];
selectedBook: Book;
display: boolean = false;
selectedUser: User;

constructor(public dataService: DataService) { }

ngOnInit() {
  this.dataService.getData();
  //Save data in local component arrays
  this.books = this.dataService.books;
  this.users = this.dataService.users;
  this.cards = this.dataService.cards;

  console.log(this.books); // ==> "undefined"
  }
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The arrays assigned within the component (after the service call) will already be executed before the service with getData() completes subscribing to the three observables. That is why they are assigning to undefined data.

In your service, modify it to return just the observable:

getData() {
  const observableList: Observable<any>[] = [];

  observableList.push(this.getBooks());
  observableList.push(this.getUsers());
  observableList.push(this.getCards());

  return forkJoin(observableList);
}

In your component then subscribe to the joined data calling getDate() within a subscriber:

this.dataService.getData()
  .subscribe(({resultOne, resultTwo, resultThree}) => {
     //Save data in local component arrays
     this.books = resultOne;
     this.users = resultTwo;
     this.cards = resultThree;
  });
}
over 4 years ago · Santiago Trujillo 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