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

448
Visualizações
Angular make subscribe to wait for response

I'm trying to subscribe to an Observable and assign some data from the response, but somehow my code it's not waiting for the response. Basically the console.log(this.newIds) is runned first and is always empty because the subscribe doesn't wait for response to come from the backend. How I can force my code to wait for the response to come?

 this.repository.getById(Ids).subscribe((response) => {
      console.log(response);
      this.newIds = response.map((id) => {
        return id;
      });
    });
    console.log(this.newIds);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can do like this..

your component file like below

newIds: Observable<any> = of(this.id).pipe(
concatMap((id) =>
  this.getId(id).pipe(map((data) => data.map((rowId) => rowId.id)))
)
);
getId(id: any) {
  return of([{ id: 1 }, { id: 2 }, { id: 3 }]);
}

your html file like below, and use async pipe for subscription. here you can use concateMap pipe rxjs operator to sequentially calling observable and then assing value to your newId varible.

<pre>
  {{ newIds | async }}
</pre>

Demo in this live link Stackblitz Link

about 4 years ago · Juan Pablo Isaza Relatório

0

If you put the code in the subscribe callback. It will execute after your receive a response from the back-end. All code you write outside this function is directly execute.

     this.repository.getById(Ids).subscribe((response) => {
          //Code will execute when back-end will respond
          console.log(response);
          this.newIds = response.map((id) => {
            return id;
          });
          console.log(this.newIds);
        });
//Code will execute immediately

See also : https://angular.io/guide/observables#creating-observables

about 4 years ago · Juan Pablo Isaza Relatório

0

This is the normal behaviour because your console.log(this.newIds); is outside of the subscription, you just need to move it inside the .subscribe() method:

 this.repository.getById(Ids).subscribe((response) => {
          console.log(response);
          this.newIds = response.map((id) => {
            return id;
          });
          console.log(this.newIds);
    });

if you want to use this.newIds outside the subscription and immediately after the result of the observer you can use RxJs .toPromise() to use it as a promise and change the method to async:

async callerFn(){

    const response = await this.repository.getById(Ids).toPromise();
  
    this.newIds = response.map((id) => {
        return id;
    });
    console.log(this.newIds);
    // use your property here

 }
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