2017-06-04 32 views
0

伙计们,我正在处理需要过滤JSON的项目,但在Chrome的开发人员工具中,它向我显示未定义属性的错误。Angular 2 - 使用Array.filter无法读取未定义错误的属性

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

}

回答

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

为什么图表变为空? – Adnan

+0

@ Sajeetharan我没有得到,this.charts是在getcharts()方法的外部声明,所以它可能不会在订阅后变为null – Adnan

+0

@Sajeedtharan是的,但它会得到错误:类型'JsonChart []'不能分配给类型'(error:any)=> void''的参数。 类型'JsonChart []'不提供匹配签名'(error:any):void'。 – Adnan

0

我认为你需要发送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; 
      } 
     }) 
    } 
} 
+0

谢谢sachila,但this.charts变为null – Adnan

相关问题