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

784
Visualizações
Angular 12 How To Call Multiple Rest API Using Subscribe Method

We need to call multiple REST API from ngOnInit() One by one. After calling first one we need to pass this response in second API call and same for the third one we need to get the value from second API call and pass it third one.

But while calling like below we are getting always undefined value .

this.globalVar1 : any;
this.globalVar2 : any;
this.globalVar3 : any;

async ngOnInit() {

this.apiService.getFirstAPICall(request).subscribe(info => {
            this.globalVar1 = info; //here value is coming from API service call
}
console.log(this.globalVar1); //here undefined 

//Now calling the second API ** here we need this first variable 
//but due to undefined we are getting error

this.apiService.getSecondAPICall(request.globalVar1).subscribe(info => {
            this.globalVar2 = info;
}
console.log(this.globalVar2); //here undefined 


over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You are running asynchronous code, that means your requests can be executed in parallel, then it happens that you make the second request before the results of the first are here.

There are several ways to make your code run sequentially, one would be to use the await keyword. This waits for the code in the current line to finish before exectuting the next line.

Your code would then look like this:

this.globalVar1 : any;
this.globalVar2 : any;
this.globalVar3 : any;

async ngOnInit() {

  this.globalVar1 = await this.apiService.getFirstAPICall(request);
  console.log(this.globalVar1);

  this.globalVar2 = await this.apiService.getSecondAPICall(this.globalVar1);
  console.log(this.globalVar2);
}

Another way to solve the problem would be to make the second request in the subscribe of the first.

over 4 years ago · Santiago Trujillo Relatório

0

Subscribe is asynchronous meaning it will not wait until it executes to fire the next line of your code. Instead you should convert your .subscribe() into a promise. Usually using the .toPromise().

Then you can await on the promises and assign the value to a parameter that you could pass to the next execution.

example

async ngOnInit() {
    const res1 = await this.apiService.getData(); // getData() should already be a promise returning a value of type Promise<YourType>
    const res2 = await this.apiService.getData2(res1);
    // etc...
}
over 4 years ago · Santiago Trujillo Relatório

0

You can use rxjs switchMap operator, you can then pass the data from first call to the inner observable (second call). you don't need then any global variables and no converting to a promise since httpClient returns an Observable

import { switchMap } from 'rxjs/operators';
...

this.apiService.getFirstAPICall(request).pipe(
  map(response1 => // edit your data here)
  switchMap((editedResponse1) => this.getSecondAPICall(editedResponse1) )
).subscribe()
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