Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
Después de completar el objeto, quiero usar los campos para obtener datos para otro objeto

He llenado mi contrato de objeto cuando uso el depurador. Puedo ver que ha llenado el objeto. Pero luego, cuando quiero usar los campos de objetos, pero no está definido. No entiendo por qué este es el caso. Aquí está la línea en cuestión donde el contrato no está definido.

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

Y aquí está mi código completo

 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 answers
Answer question

0

En ngOnInit() llamas a this.GetContractClient()

DESPUÉS

En GetContractClient llamas a this.GetContract(this.contractNumber)

El código en GetContract es código asíncrono. Esto significa que no se ejecuta inmediatamente. Por ejemplo, si digo "Estoy haciendo una taza de café" no sucede instantáneamente. La tetera tarda un rato en hervir. Lo mismo con el código asíncrono. No ha proporcionado información sobre lo que está haciendo su servicio, pero supongo que realiza una llamada HTTP a su servidor. Esto lleva tiempo. Este código asíncrono comienza a ejecutarse pero el resto del código no espera a que termine de ejecutarse. Continúa. Por lo tanto, el código:

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

Ejecuta a continuación.

Sin embargo, el bloque de suscripción aquí aún no se ha ejecutado. SOLO SE EJECUTA CUANDO SE COMPLETA LA LLAMADA HTTP.

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

Entonces, el código this.contract = result aún no se ha ejecutado, por lo que el contrato no está definido en esta línea:

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

Para arreglarlo haz esto:

 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) });

Espero que te ayude a entender el código asíncrono.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!