尝试按角度过滤数组,出现以下控制台错误:
TypeError:无法读取未定义的属性“ filter”
我的课程代码在下面
export class FetchDataComponent {
public forecasts: WeatherForecast[];
public cacheForecasts: WeatherForecast[];
public summaries: any[];
constructor(http: HttpClient) {
http.get<WeatherForecast[]>(BaseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
this.forecasts = result;
}, error => console.error(error));
http.get<any[]>(BaseUrl + 'api/SampleData/GetSummaries').subscribe(result => {
this.summaries = result;
}, error => console.error(error));
}
filterForeCasts(filterVal: any) {
if (filterVal === '0') {
this.forecasts = this.cacheForecasts;
} else {
this.forecasts = this.cacheForecasts.filter((item) => item.summary === filterVal); // <--- error here
}
}
}
我在这里做什么错了?
答案 0 :(得分:2)
尝试将cacheForecasts:WeatherForecast []初始化为一个空数组。如果构造函数调用的getWeather请求失败,则cacheForecasts将是未定义的
答案 1 :(得分:0)
我意识到构造函数缺少过滤数组的初始化,因此以下代码可以正常工作:
constructor(http: HttpClient) {
http.get<WeatherForecast[]>(BaseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
this.forecasts = result;
this.cacheForecasts = result;
}, error => console.error(error));
http.get<any[]>(BaseUrl + 'api/SampleData/GetSummaries').subscribe(result => {
this.summaries = result;
}, error => console.error(error));
}