伙计们,我正在开发一个需要过滤JSON的项目,但是在Chrome的开发者工具中,它显示了一个未定义属性的错误。
chart: JsonChart[] = [];
charts: JsonCharts[] = [];
getCharts() {
this.iChartHttp.getCharts()
.subscribe(
charts => this.charts = charts, //return json object
error => this.errorMessage = <any>error
);
}
if (this.chart_id != null) {
this.getCharts();
this.chart = this.charts.filter(charts => charts.id === this.chart_id)[0].series; // this like error occur.
}
更新问题
它没有从服务中获取JSON数组。但它适用于另一个组件
iChartHttpService:
getCharts(): Observable<JsonCharts[]> {
return this.http.get('assets/datas.json')
.map((res: Response) => res.json())
.do(data => console.log('server data:', data)) // debug
.catch(this.handleError);
}
/**
* Handle HTTP error
*/
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
答案 0 :(得分:2)
当图表为空时发生,尝试在结果之后放置过滤器逻辑,
getCharts() {
this.iChartHttp.getCharts()
.subscribe((charts: any) => {
this.charts = charts, //return json object
this.chart = this.charts.filter(charts => charts.id === this.chart_id)[0].series;
}, error => {
error => this.errorMessage = <any>error
});
}
答案 1 :(得分:1)
我认为您需要在javascript过滤器函数中发送该系列。像这样修改它
if (this.chart_id != null) {
this.getCharts();
if (this.chart.length > 0) {
this.chart = this.charts.filter(charts => {
if (charts.id === this.chart_id) {
charts[0].series;
}
})
}
}