I have a function which has an API call inside an 'if' condition.When I execute that function, before completing the API response, the program moves to below code lines.That breaks the functional flow since some below codes are running before API response comes Below is my code.
change(event: any) {
let selectedUnitIds = event.source.value;
let newUnitIds = this.getNewUnitIds(selectedUnitIds);
if (newUnitIds.length !== 0) {
this.commonServerService.getOrgUnitById(newUnitIds).subscribe(orgUnits => {
orgUnits.forEach(unit =>
this.unitMap.set(unit.id, unit)
);
});
}
//get selected ids' orgunits
let selectedOrgUnits = this.getSelectedUnits(selectedUnitIds);
// get tribes of those orgunits
let need = this.getNeededTribes(selectedOrgUnits);
}
The problem here is the if condition. If this API is called unconditionally, inside the subscribe method, everything is working asynchronously. Please guide me through this.
later added:- common-server.service.ts
getOrgUnitById(id: string[]): Observable<Array<OrgUnit>>
{
return this.orgUnitService.findOrgUnitByIds(id);
}