网站搜索

angular - 在填充对象后,我想使用这些字段来获取另一个对象的数据


当我使用调试器时,我已经填充了我的对象 Contract,我可以看到它已经填充了对象。但后来当我想使用对象的字段时,它是未定义的。我不明白为什么会这样。这里是相关的代码行,contract 是未定义的。

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

这是我的完整代码

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

答案#1

在 ngOnInit() 中,你调用 this.GetContractClient()

然后

在 GetContractClient 中,你调用了 this.GetContract(this.contractNumber)

GetContract 中的代码是异步代码。这意味着它不会立即执行。例如,如果我说“我正在泡一杯咖啡”,它不会马上发生。烧水壶需要一段时间。同样的道理适用于异步代码。你没有提供你的服务具体在做什么的信息,但我猜它会向你的服务器发起一个 HTTP 请求。这是需要时间的。这段异步代码开始执行,但其他代码不会等待它完成执行,会继续运行。因此,代码:

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

执行下一个。

然而,这里的订阅块尚未执行。它只有在 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)
});

所以这段代码 this.contract=result 还没有执行,这就是为什么在这一行中 contract 是未定义的原因:

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

要修复它,请这样做:

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

希望这能帮助你理解异步代码。