![](/img/trans.png)
[英]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.