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

174
Visualizações
After populating the object I want to use the fields to get data for a other object

I have populated my object Contract when using the debugger I can see it has populated the object. But later when I want to use the objects fields but it is undefined. I do not understand why this is the case. Here is the line in question where contract is undefined.

console.log("test id contract client" + this.contract.contractId);

And Here is my full code

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Client } from '../../models/client';
import { Contract } from '../../models/Contract';
import { ClientService } from '../../services/client.service';
import { ContractService } from '../../services/contract.service';

@Component({
  selector: 'app-contract-customer',
  templateUrl: './contract-customer.component.html',
  styleUrls: ['./contract-customer.component.css']
})
export class ContractCustomerComponent implements OnInit {
  public contractNumber: string;
  public client: Client;
  public contract: Contract;

  constructor(private route: ActivatedRoute, private clientService: ClientService, private contractService: ContractService) { }


  ngOnInit():void  {
    // First get the contract id from the current route.
    const url = window.location.href;
    var parts = url.split('/', 6);

    this.contractNumber = parts[4];

    console.log("Contract Id form url : " + this.contractNumber);

    this.GetContractClient();

  }


  GetContract(id: string) {
    this.contractService.getContract(Number(id)).subscribe(result => {
      this.contract = result;
    }, error => {
      console.log(error)
    });
  }

  GetContractClient() {
    this.GetContract(this.contractNumber);

    console.log("test id contract client" + this.contract.contractId);

    this.clientService.getClient(this.contract.contractId).subscribe(result => {
      this.client = result;
    }, error => {
      console.log('something wrong here!!!')
        console.log(error)
    });
    }
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In ngOnInit() you call this.GetContractClient()

THEN

In GetContractClient you call this.GetContract(this.contractNumber)

The code in GetContract is asynchronous code. This means that it does not execute immediately. For example, if I said "I'm making a cup of coffee" it does not happen instantly. It takes a while for the kettle to boil. Same with asynchronous code. You haven't provided information about what your service is doing but I am guessing it makes an HTTP call to your server. This takes time. This asynchronous code starts to execute but the rest of the code does not wait for it to finish execution. It continues. Hence, the code:

console.log("test id contract client" + this.contract.contractId);

Executes next.

However, the subscribe block here has not yet been executed. IT ONLY EXECUTES WHEN THE HTTP CALL COMPLETES.

this.contractService.getContract(Number(id)).subscribe(result => {
  // IMPORTANT: THIS LINE ONLY EXECUTES WHEN THE HTTP CALL COMPLETES
  this.contract = result;
}, error => {
  console.log(error)
});

So the code this.contract = result has not yet been executed which is why contract is undefined on this line:

console.log("test id contract client" + this.contract.contractId);

To fix it do this:

this.contractService.getContract(Number(id)).subscribe(result => {
  // IMPORTANT: THIS LINE ONLY EXECUTES WHEN THE HTTP CALL COMPLETES
  this.contract = result;
  console.log("test id contract client" + this.contract.contractId);
}, error => {
  console.log(error)
});

Hope that helps you to understand asynchronous code.

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