[英]how to get data from nested json in angular material tables ? - ANGULAR
[英]Angular 5 how to get data from Nested Json file
尝试从嵌套的json获取数据。
Error: 1. <h3>{{sampledata}}</h3> displaying [object Object]
2. <p>{{sampleDataModel.Title}}</p> ERROR TypeError: Cannot read property 'Title' of undefined
资料夹结构:
sampledata.json:
{
"isSuccessfull": true,
"Model": [
{
"SampleDataModel": [
{
"Title": "SampleData 1",
"Description": "Some Text"
}
],
"SampleDetailModel": [
{
"Name": "Donald Trump",
"Id": "111",
"Country": "USA"
}
]
}
]
}
sampledata.services.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class SampledataService {
private _url = 'assets/data/sampledata.json'
constructor(private _http: Http) { }
getData(){
return this._http.get(this._url)
.map((resSampleData: Response) => resSampleData.json());
}
}
sampledata.component.ts:
import { Component, OnInit } from '@angular/core';
import { SampledataService } from '../sampledata.service'
@Component({
selector: 'app-sampledata',
templateUrl: './sampledata.component.html',
styleUrls: ['./sampledata.component.css']
})
export class SampledataComponent implements OnInit {
sampledata = [];
sampleDataModel = [];
sampleDetailModel = [];
constructor(private _sampledataservice: SampledataService) { }
ngOnInit() {
this._sampledataservice.getData()
.subscribe(resData => {
this.sampledata = resData;
this.sampleDataModel = resData.Model.SampleDataModel;
this.sampleDetailModel = resData.Model.SampleDetailModel });
}
}
sampledata.component.html:
<h3>{{sampledata}}</h3>
<p>{{sampleDataModel.Title}}</p>
app.module.ts:
declarations: [
AppComponent,
SampledataComponent
],
imports: [
BrowserModule, HttpClientModule, HttpModule
],
providers: [HttpClientModule, SampledataService],
angular-cli.json:
"assets": [
"assets",
"assets/data/sampledata.json",
"favicon.ico"
],
我的问题是:
sampledata和sampleDataModel.Title?
如果您对解决此问题有任何想法,请帮助向我建议解决方案,谢谢。
似乎问题出在这里private _url = 'assets/sampledatajson'
您可能需要加一个点.
像这样的json
之前
private _url = 'assets/sampledata.json'
在您的sampledata.component.html
您绑定了错误的变量...绑定sampledata
而不是sampledataModel
。 因为在订阅中,您正在为this.sampledata
分配值。
您需要仔细查看JSON并确切查看属性的位置。您可以使用以下方法访问所需的数据:
this.sampledata = resData;
this.sampleDataModel = resData.Model[0].SampleDataModel[0];
this.sampleDetailModel = resData.Model[0].SampleDetailModel[0];
然后要显示没有迭代或其他任何操作的sampleData
,请使用json
管道:
<pre>{{sampledata | json}}</pre>
<p>{{sampleDataModel?.Title}}</p>
另外,所有变量都是声明了对象的对象,而不是数组,所以...
sampledata = {};
sampleDataModel = {};
sampleDetailModel = {};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.