Angular 5如何从嵌套JSON获取数据及报错问题排查
解决Angular 5中嵌套JSON数据渲染的两个问题
我来帮你搞定这两个头疼的问题,先拆解一下你的JSON结构和代码里的核心问题:
首先看你的sampledata.json结构,它的层级是这样的:
{
"isSuccessfull": true,
"Model": [ // 这是一个数组
{
"SampleDataModel": [ // 又是一个数组
{ "Title": "SampleData 1", "Description": "Some Text" }
],
"SampleDetailModel": [
{ "Name": "Donald Trump", "Id": "111", "Country": "USA" }
]
}
]
}
问题1:渲染{{sampledata}}显示[object Object]
这是很常见的问题,因为sampledata是一个JavaScript对象,Angular直接插值时会调用对象的toString()方法,默认返回就是[object Object]。
解决办法:
- 如果只是想查看整个JSON的结构,可以用
JSON.stringify()把对象转成字符串:<h3>{{ JSON.stringify(sampledata) }}</h3> - 正常场景下,我们需要访问对象的具体属性,而不是渲染整个对象,这就关联到第二个问题的解决。
问题2:{{sampleDataModel.Title}}触发TypeError: Cannot read property 'Title' of undefined
这个报错有两个核心原因:
- 数据异步加载的时序问题:你的数据是通过HTTP请求获取的,初始时
sampledata(或sampleDataModel)还没被赋值,处于undefined状态,直接访问它的属性就会报错。 - JSON嵌套数组的访问路径错误:你的
SampleDataModel是嵌套在Model数组里的子数组,不是直接的顶层属性,所以直接写sampleDataModel.Title完全找不到对应的属性。
解决办法:
第一步:确保服务正确获取数据
先补全你的sampledata.services.ts代码(假设JSON文件放在assets目录下):
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class SampledataService { constructor(private http: HttpClient) { } getSampleData(): Observable<any> { return this.http.get('./assets/sampledata.json'); } }
第二步:组件中订阅数据
在组件(比如AppComponent)中注入服务并获取数据:
import { Component, OnInit } from '@angular/core'; import { SampledataService } from './sampledata.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit { sampledata: any; constructor(private dataService: SampledataService) { } ngOnInit(): void { this.dataService.getSampleData().subscribe(data => { this.sampledata = data; }); } }
第三步:模板中正确访问嵌套属性
用**安全导航操作符?.**解决异步加载时的undefined问题,同时按照JSON的层级路径访问:
<!-- 单个元素的情况:访问Model数组第一个元素里的SampleDataModel第一个元素的Title --> <p>{{ sampledata?.Model[0]?.SampleDataModel[0]?.Title }}</p> <p>{{ sampledata?.Model[0]?.SampleDataModel[0]?.Description }}</p> <!-- 如果有多个元素,用*ngFor遍历数组 --> <div *ngFor="let modelItem of sampledata?.Model"> <h4>Sample Data:</h4> <div *ngFor="let dataItem of modelItem?.SampleDataModel"> <p>Title: {{ dataItem.Title }}</p> <p>Description: {{ dataItem.Description }}</p> </div> <h4>Sample Detail:</h4> <div *ngFor="let detailItem of modelItem?.SampleDetailModel"> <p>Name: {{ detailItem.Name }}</p> <p>ID: {{ detailItem.Id }}</p> <p>Country: {{ detailItem.Country }}</p> </div> </div>
关键要点:
?.操作符会在属性为null或undefined时停止访问,避免报错。- 一定要注意JSON里的数组结构,
Model和SampleDataModel都是数组,必须通过索引(比如[0])或者*ngFor遍历才能访问里面的元素。
内容的提问来源于stack exchange,提问作者Puneeth
相关产品推荐
相关产品推荐

