角度 7 - 类型错误:无法读取未定义的属性"过滤器"



试图以角度过滤数组,我得到以下控制台错误:

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

我在这里做错了什么?

尝试将cacheForecasts:WeatherForecast[]初始化为空数组。如果构造函数调用的getWeather请求失败,那么cacheForecasts将是未定义的

我意识到构造函数缺少筛选数组初始化,所以下面的代码运行得很好:

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

相关内容

最新更新