我有一个非常奇怪的问题,我无法弄清楚,当使用“ 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"
}
]
}
答案 0 :(得分:1)
我认为这是因为在您的订阅中填充了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()
});