angular - Chyba TypeScriptu - Typ '{}' není typ pole ani typ řetězce
Mám následující kód:
forkJoin([
this.restangular.all(this.commonService.getHospitalURI()).getList(),
this.restangular.all(this.commonService.getAgeGroupURI()).getList()
]).subscribe(responses => {
const hospital_result = responses[0];
// Error because of the line below
const agegroup_result = Array.from(responses[1]);
console.log('hospital ' + JSON.stringify(hospital_result))
console.log('agegroup ' + JSON.stringify(agegroup_result))
for (const productID_hospital of hospital_result[0]['product']) {
for (const productID_agegroup of agegroup_result) {
// Do Something here
}
}
})
Používám Angular 5 a dělám forkjoin pro volání odpovědi sekvenčně. Tato část je úplně v pořádku. Ale chyba nastává, když se snaží analyzovat JSON.
Dostanu tuto chybu:
src/app/layout/insurance-list/insurance-list.component.ts(75,48): error TS2345: Argument of type '{}' is not assignable to parameter of type 'Iterable<{}>'.
Property '[Symbol.iterator]' is missing in type '{}'.
Pokud se změní
const agegroup_result = Array.from(responses[1]);
to
const agegroup_result = responses[1];
Pak dostanu chybu:
src/app/layout/insurance-list/insurance-list.component.ts(85,50): error TS2495: Type '{}' is not an array type or a string type.
Nerozumím, proč mám tuto chybu. JSON parsuji správně, protože nejdříve vrací pole. Kvůli této chybě nemohu spustit svůj projekt.
Upravit :
Zde je odkaz na JSON pro agegroup_result: https://plnkr.co/edit/hzkPXqWfGmNNgHuHwAzT?p=catalogue
Je pojmenován jako agegroup.json
Úprava 2:
console.log(responses[1] instanceof Array)
Výše uvedený kód vrací pravda. Response[1] je pole.
Odpověď č. 1
Snažil jsem se namapovat můj typ dat „any“ na konkrétní typ DataModel a dostal jsem stejnou chybovou zprávu. Takže pro vyřešení problému navrhuji místo toho použít index pole, tady to je:
Změňte tento řádek kódu:
const agegroup_result = Array.from(responses[1]);
Komu :
const ages = responses[1];
Pak když budete dělat smyčku „for“, použijte prosím index pole:
for ( const i of Object.keys(ages)){
console.log(ages[i].propertyName);
}
Doufám, že to může pomoci vyřešit váš problém.
Odpověď č. 2
Je to objekt, ne pole. Zkuste získat všechny klíče z objektu pomocí funkce Object.Keys.
const agegroup_result = Object.keys(responses);
pak můžete iterovat přes klíče objektu responses, nebo můžete mapovat odpověď na typ pole.
pokud přidáte konzolový zápis objektu responses a požadovaného očekávaného objektu/array, můžeme možná být schopni trochu více pomoci.
