[英]Angular 5 - Error getting data from local JSON file [object Object]
我正在尝试从sampledata.json获取数据
错误:
{{sampledata}}
显示[object Object]
{{sampleDataModel.Title}}
错误TypeError:无法读取未定义的属性“ Title” sampledata.json:
{
"isSuccessfull": true,
"Model": [
{
"SampleDataModel": [
{
"Title": "SampleData 1",
"Description": "Description."
}
],
"SampleDetailModel": [
{
"name": "Donald Trump",
"id": "111",
"country": "USA"
}
]
}
]
}
sampledata.services.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
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>
<p>{{sampleDetailModel.name}}</p>
我的问题是:
如何显示这些值?
如果您对解决此问题有任何想法,请帮助向我建议解决方案,谢谢。
<h3>{{sampledata | json}}</h3> // pipe | json needed to show object as stringyfied
<p>{{sampleDataModel[0]?.Title}}</p> // ? to check if object is not null or undefined
<p>{{sampleDetailModel[0]?.name}}</p>
并如下所示进行更改
this.sampledata = resData;
this.sampleDataModel = resData.Model[0].SampleDataModel;
this.sampleDetailModel = resData.Model[0].SampleDetailModel
也许您应该尝试以下操作:在ngOnInit中获取数据时:
this._sampledataservice.getData()
.subscribe(resData => {
this.sampledata = resData;
this.sampleDataModel = resData.Model[0].SampleDataModel;
this.sampleDetailModel = resData.Model[0].SampleDetailModel });
...以及HTML:
<h3>{{sampledata}}</h3>
<p>{{sampleDataModel[0].Title}}</p>
<p>{{sampleDetailModel[0].name}}</p>
根据OP中的代码很少观察到:
访问SampleDataModel
要访问SampleDataModel
属性,它应该是resData.Model[0].SampleDataModel
而不是resData.Model.SampleDataModel
。
{{sampleDataModel.Title}}错误TypeError:无法读取未定义的属性“ Title”
访问SampleDataModel
数组的Title
属性。 应该是{{sampleDataModel[0].Title}}
而不是{{sampleDataModel.Title}}
。
this.sampleDataModel = resData.Model[0].SampleDataModel;
{{sampledata}}显示[object Object]
由于sampledata
是JSON对象,因此显示为[object object]
。 在模板中使用之前对其进行Stringify
。
this.sampledata = JSON.stringify(resData);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.