这是我的 app.component.ts
@Component({
selector: 'my-app',
template: `<h1>{{title}}</h1>
{{test | json}}
<div ngFor='let test of tests' style='border: solid 1px'>
<div>
<P>
writer: {{test.A.B.C.D.writerid}} <br>
content:{{test}}<br>
write_date:{{test}}</P>
</div>
</div>
`,
})
public test: any[] = [
{
'A': {
'B': [{
'C': {
'D': [{
'content': 'content_test1',
'writedt': '2017-02-08 00:00:00',
'writerid': 'writerid_test1'
}, {
'content': 'content_test2',
'writedt': '2017-02-08 00:00:00',
'writerid': 'writerid_test1'
}, {
'content': 'content_test3',
'writedt': '2017-02-08 00:00:00',
'writerid': 'writerid_test2'
}, {
'content': 'content_test4',
'writedt': '2017-02-08 00:00:00',
'writerid': 'writerid_test2'
}]
}
}]
}
}
];
test.A.B.C.D.writerid 不工作 错误:无法读取未定义的属性“B” 我不明白为什么错误不是 A 而是 B 我如何访问 D 的内容或 writedt 或 writerid
最佳答案
首先,我假设您的模板中有一些拼写错误(例如 ngFor
),并且该数组实际上称为 tests
但让我们忽略它。
我猜您想遍历 D
的数组。 无需对数据结构进行任何更改,您可以使用嵌套的 *ngFor
:s 来完成。
所以首先你的数组应该命名为tests
,而不是test
。以及如何访问最内层数组,我们将首先遍历 tests
数组,然后遍历数组 B
,最后遍历最内层数组 D
。
所以你的模板看起来像这样:
<div *ngFor="let test of tests">
<div *ngFor="let x of test.A.B">
<div *ngFor="let y of x.C.D; let i = index"> <h4>Content {{i+1}}</h4>
{{y.content}}
{{y.writedt | date}}
{{y.writerid}}
</div>
</div>
</div>
DEMO
关于json - 我如何访问angular2中嵌套的json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43204434/