Ionic调用filterCategory出现filter未定义错误求助
嘿,我之前也遇到过一模一样的问题!你猜的没错,就是因为调用filterCategory的时候,数据源还没完成异步加载,导致filter方法调用在了undefined上。咱们来一步步解决这个问题:
具体解决方案
1. 给数据源加初始值,避免undefined
首先在你的CategoriesProvider里,先把要过滤的数据源初始化成一个空数组,这样哪怕数据还没加载,它也不会是undefined:
// CategoriesProvider 中的代码 export class CategoriesProvider { // 初始化为空数组,而不是默认的undefined private categories: any[] = []; constructor(private http: Http) {} // 加载数据的方法(假设你是用HTTP请求获取数据) loadCategories() { return this.http.get('你的数据接口地址') .map(res => res.json()) .subscribe(data => { // 数据返回后再赋值给categories this.categories = data; }); } filterCategory(filterText: string) { // 现在categories至少是空数组,调用filter不会报错 return this.categories.filter(category => { // 这里写你的过滤逻辑,比如匹配分类名称 return category.name.toLowerCase().includes(filterText.toLowerCase()); }); } }
2. 确保数据加载完成后再调用过滤方法
在你的页面组件里,一定要等数据加载完成后再调用filterCategory,比如在loadCategories的订阅完成后执行:
// 你的页面组件代码 import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { CategoriesProvider } from '../../providers/categories/categories'; @IonicPage() @Component({ selector: 'page-your-page', templateUrl: 'your-page.html', }) export class YourPage { filteredCategories: any[]; constructor( public navCtrl: NavController, public navParams: NavParams, private categoriesProvider: CategoriesProvider ) {} ionViewDidLoad() { // 先加载数据,完成后再执行过滤 this.categoriesProvider.loadCategories().subscribe(() => { this.filteredCategories = this.categoriesProvider.filterCategory('你要过滤的关键词'); }); } }
3. 快捷方案:给filter加空值保护
如果不想调整调用顺序,也可以直接在filterCategory方法里做短路处理,确保调用filter的是一个数组:
filterCategory(filterText: string) { // 如果categories是undefined或null,就用空数组替代 return (this.categories || []).filter(category => { return category.name.toLowerCase().includes(filterText.toLowerCase()); }); }
这样哪怕数据还没加载,(this.categories || [])会返回空数组,调用filter就不会抛出Cannot read property 'filter' of undefined的错误了。
内容的提问来源于stack exchange,提问作者Shah Rushabh
相关产品推荐
相关产品推荐

