I have very very strange issue that I can't figure out, when using "Chrome" my object sometimes becomes null but in IE it always works. It happens only for all my drop downs,however, other control like textbox are working as expected...here is a simplified version of my code.
note: dropdrown is binding correctly, so the values are available in the html
HTML (Using Reactive forms)
<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"
}
]
}
I would assume it's because iCostCenter
is populated inside your subscription and populateHeaderDet()
is being called before the response comes back from getAllCostCenters()
.
Try calling populateHeaderDet()
after you assign iCostCenter instead
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)
)};
From the comments it sounds like what you actually want to do is wait for muliple observables to complete before you call the populateHeaderDet()
method. One approach to solving this would be to use the rxjs zip method.
As I haven't seen the rest of your code then it's difficult to say for sure but you could try something like this
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()
});