Angular 2 - 无法使用 Array.filter 读取 属性 的未定义错误

Angular 2 - Cannot read property of undefined error using Array.filter

伙计们,我正在做一个需要过滤 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);

}

图表为空时会发生,请尝试将您的筛选逻辑放在结果之后,

  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 过滤功能中发送系列。像这样修改它

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;
            }
        })
    }
}