对象在 Chrome 中为空,在 IE 中不为空

objec is null in Chrome and not null in IE

我有一个非常非常奇怪的问题,我无法弄清楚,当使用 "Chrome" 时,我的对象有时会变为空,但在 IE 中它总是有效。它只发生在我所有的下拉列表中,但是,文本框等其他控件按预期工作...这是我的代码的简化版本。

注意:dropdrown 绑定正确,因此值在 html

中可用

HTML(使用响应式表单)

     <label for="costCenterId" class="control-label">Cost Center</label>

    <p-dropdown [options]="iCostCenter" optionLabel="cost_center_name"  styleClass="form-control"
 formControlName="costCenter" id="costCenterId" name="costCenter" dataKey="cost_center_id"
          [filter]="true" filterBy="value.cost_center_name">
 </p-dropdown>

TS

    export interface ICostCenter{

        cost_center_id: number,
        cost_center_name: string
    }

    iCostCenter: ICostCenter[]=[];

    ngOnInit() {
     this.getAllCostCenetrs();
this.populateHeaderDet();

    }

    getAllCostCenetrs() {
            this._appParams.getAllCostCenters()
                .subscribe(
                data => {
                    this.iCostCenter = data.result;


                },
               error => 'GetAllCostCenetrs Method: ');

        }

populateHeaderDet() in chrome iCostCenter become null
    {
    this.ersaForm.patchValue({

                   costCenter: this.iCostCenter.find(cc => cc.cost_center_name === this.iRequest.costCenter.cost_center_name)

)};

JSON

{
  "result": [
    {
      "cost_center_id": 1,
      "cost_center_name": "1"
    },
    {

      "cost_center_id":2,
      "cost_center_name": "2"
    }
   ]
}

我认为这是因为 iCostCenter 填充在您的订阅中,并且 populateHeaderDet() 在响应从 getAllCostCenters() 返回之前被调用。

在分配 iCostCenter 后尝试调用 populateHeaderDet()

ngOnInit() {
    this.getAllCostCenetrs();
}

getAllCostCenetrs() {
    this._appParams.getAllCostCenters().subscribe(
        data => {
            this.iCostCenter = data.result;
            this.populateHeaderDet();
            },
            error => 'GetAllCostCenetrs Method: ');
    }

populateHeaderDet()
{
    this.ersaForm.patchValue({
               costCenter: this.iCostCenter.find(cc => cc.cost_center_name === this.iRequest.costCenter.cost_center_name)
)};

编辑

从评论看来,您实际上想要做的是等待多个可观察对象完成,然后再调用 populateHeaderDet() 方法。解决此问题的一种方法是使用 rxjs zip 方法。

因为我还没有看到你的其余代码,所以很难确定,但你可以尝试这样的事情

const costCentres$ = this._appParams.getAllCostCenters();
const companyCodes$ = this._appParams.getAllCompanyCodes()

zip(
 costCentres$,
 companyCodes$,
 (costCentres: string[], companyCodes: string[]) => ({costCentres, companyCodes}))
 .subscribe(data => {
   this.iCostCenter = data.costCentres;
   this.companyCodes = data.companyCodes;

   this.populateHeaderDet()
 });