伙计们,我正在做一个需要过滤 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);
最佳答案
当 charts 为 null 时会发生,请尝试将您的过滤逻辑放在结果之后,
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
});
}
关于javascript - Angular 2 - 无法使用 Array.filter 读取未定义错误的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44353895/