[英]Type 'string | string[]' is not assignable to type 'string' - typescript type error
[英]TypeScript Error - Type '{}' is not an array type or a string type
我有以下代碼:
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
}
}
})
我正在使用Angular 5,使用forkjoin按順序調用響應。 這部分完全沒問題。 但是當它試圖解析JSON時會出現錯誤。
我收到此錯誤:
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 '{}'.
如果我改變
const agegroup_result = Array.from(responses[1]);
至
const agegroup_result = responses[1];
然后我會收到一個錯誤:
src/app/layout/insurance-list/insurance-list.component.ts(85,50): error TS2495: Type '{}' is not an array type or a string type.
我不明白為什么我有這個錯誤。 我正在解析JSON,因為它首先返回一個數組。 由於此錯誤,我無法運行我的項目。
編輯:
以下是agegroup_result的JSON鏈接: https ://plnkr.co/edit/hzkPXqWfGmNNgHuHwAzT ? p = catalogue
它被命名為agegroup.json
編輯2:
console.log(responses[1] instanceof Array)
上面的代碼返回true。 響應[1]是一個數組。
我試圖將我的“任何”類型的數據映射到特定的DataModel類型,我得到了相同的錯誤消息。 所以,為了解決這個問題,我建議你使用數組的索引,這里我們去:
更改此行代碼:
const agegroup_result = Array.from(responses[1]);
至:
const ages = responses[1];
然后當你做“for”循環時,請使用數組的索引:
for ( const i of Object.keys(ages)){
console.log(ages[i].propertyName);
}
我希望這有助於解決您的問題。
它是一個對象,而不是一個數組。 嘗試使用Object.Keys函數從對象獲取所有鍵。
const agegroup_result = Object.keys(responses);
然后,您可以迭代響應對象的鍵,或者可以將響應映射到數組類型。
如果你添加了一個響應對象的控制台日志和預期的所需對象/數組,那么我們可能會提供更多幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.