當我嘗試使用下面的代碼遍歷嵌套數組對象時,它不起作用。它是在Typescript或angular4中拋出錯誤「未定義」的任何問題?在角度4組件中迭代嵌套數組對象時不起作用
import { Process, Event } from "./process";
export class ProcessComponent {
process: Process;
someMethod() {
for(let val of this.process.events) {
console.log(val.notes); // throwing error in console showing undefined.
}
}
process.ts
export class Process {
id: number;
includeSaturdays: boolean;
includeSundays: boolean;
events: Event[];
}
export class Event {
id: number;
date: number;
notes: string;
}
示例數據:根據你的數據結構
{
"id": 1572734,
"includeSaturdays": false,
"includeSundays": false,
"events": {
"event": [
{
"id": 1587532,
"date": 1483209000000,
"notes": "New year"
},
{
"id": 1587533,
"date": 1495909800000,
"notes": "Memorial day"
}]
}
}
在您的示例數據中,事件不是數組,而是鍵/值映射,其中鍵事件映射到對象數組 –
'for(let this.process.events.event val)'可能是您意思是這個? – jmw5598
試試這個。這應該工作。 'process:Process [];'你有json對象而不是對象數組。 – micronyks