我正在尝试从sampledata.json
获取数据错误:
{{sampledata}}
显示[object Object]
{{sampleDataModel.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>
我的问题是:
如何显示这些值?
如果您有任何想法如何解决此问题,请帮助向我推荐解决方案,谢谢。
答案 0 :(得分:3)
<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
答案 1 :(得分:1)
也许你应该试试这个: 在获取数据时在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>
答案 2 :(得分:1)
很少根据OP中的代码进行观察:
访问SampleDataModel
要访问SampleDataModel
属性,应该是resData.Model[0].SampleDataModel
而不是resData.Model.SampleDataModel
。
{{sampleDataModel.Title}} ERROR TypeError:无法读取属性 &#39;名称&#39;未定义的
访问Title
数组的SampleDataModel
属性。它应该是{{sampleDataModel[0].Title}}
而不是{{sampleDataModel.Title}}
。
this.sampleDataModel = resData.Model[0].SampleDataModel;
{{sampledata}}}显示[object Object]
由于sampledata
是一个JSON对象,它显示为[object object]
。在模板中使用之前Stringify
。
this.sampledata = JSON.stringify(resData);