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

261
Visualizações
Angular 2 - Property is undefined after subscription ended

Using angular 2+ - I have declared a public property which I am expecting to be populated with promise data object, using "ngOnInit" lifecycle method in order to send http request to my API.

in subscribe block I am assigning the property to the data received from the observable but then I want to log this property its appear as undefined outside the subscription but not undefined inside the subscription block which is odd behavior (am i missing something?) code below:

async ngOnInit(): Promise<any> {
  console.log(this.indexID);
  const elements = document.getElementsByClassName('footer-wrap');
  while (elements.length > 0){
    elements[0].parentNode.removeChild(elements[0]);
  }
  await this.landingService.getLandingDataById(this.indexID)
  .subscribe((res:any) => {
    this.landingData = res['data'][0];    
  });
  console.log(this.landingData); 
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

await this.landingService.getLandingDataById(this.indexID)
.subscribe((res:any) => {
  this.landingData = res['data'][0];    
});

doesn't make sense. .subscribe returns a subscription. You can't await it. You can't await an observable, because it can trigger multiple times, but you can convert an observable to a promise, e.g. with firstValueFrom

async ngOnInit(): Promise<void> {
  console.log(this.indexID);
  const elements = document.getElementsByClassName('footer-wrap');
  while (elements.length > 0){
    elements[0].parentNode.removeChild(elements[0]);
  }
  const res = await firstValueFrom(this.landingService.getLandingDataById(this.indexID));
  this.landingData = res['data'][0];    
  console.log(this.landingData); 
}

its appear as undefined outside the subscription but not undefined inside the subscription block which is odd behavior

That's not odd. That's the expected behavior. this.landingData = res['data'][0]; is executed after console.log(this.landingData);. this.landingService.getLandingDataById(this.indexID) returns an asynchronous observable. You can remove async / await and move the console.log into the observer:

ngOnInit(): void {
  console.log(this.indexID);
  const elements = document.getElementsByClassName('footer-wrap');
  while (elements.length > 0){
    elements[0].parentNode.removeChild(elements[0]);
  }
  this.landingService.getLandingDataById(this.indexID)
  .subscribe((res:any) => {
    this.landingData = res['data'][0];  
    console.log(this.landingData);   
  });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

TypeScript is asynchronous functions which means that TypeScript won’t wait for a function to finish before executing the code below it. In below code, First execute the 2nd log and then execute 1st log. so you will not get the return data in log

async ngOnInit(): Promise<any> {
   await this.landingService.getLandingDataById(this.indexID)
  .subscribe((res:any) => {
    this.landingData = res['data'][0];   
  console.log('data'); 
  });
  console.log(this.landingData); 
}

Try this it will work

ngOnInit(): void {
  this.landingService.getLandingDataById(this.indexID)
  .subscribe((res:any) => {
    this.landingData = res['data'][0];  
    console.log(this.landingData);   
  });
}
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