You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 14+Ionic 6搜索页面返回undefined及Pipe的filter调用报错求助

问题排查与修复方案

问题1:控制台持续返回undefined

原因

  • API返回的是纯数组,但代码中错误尝试访问data.body.products,而API响应里并没有products字段,因此输出undefined。
  • 组件内products初始化为单个对象,与API返回的数组类型不匹配。

修复(修改search.page.ts)

export class SearchPage implements OnInit {
  term = '';
  // 初始化products为空数组,匹配API返回类型
  products: any[] = [];

  constructor(
    private searchService: SearchService,
  ) { }

  ngOnInit() {
    this.search(this.term);
  }

  search(term: string) {
    this.searchService.searchCall(term).subscribe(
      (data: any) => {
        // API返回的数组直接赋值给products
        this.products = data.body;
        console.log('Search results:', this.products);
      },
      error => {
        console.log('Error', error);
      }
    );
  }
}

问题2:输入文本后出现TypeError: Cannot read properties of undefined (reading 'filter')

原因

  • 模板中错误使用products?.results遍历数据,API返回的数组没有results属性,导致传给FilterPipe的value为undefined,调用filter方法时报错。
  • FilterPipe未处理value为undefined/null的情况,直接执行value.filter。
  • 搜索框仅绑定了ngModel,未触发搜索方法,输入文本后不会更新数据。

修复步骤

1. 修改search.page.html

<ion-content [fullscreen]="true" class="ion-padding">
  <!-- 添加ngModelChange事件,输入文本时触发搜索 -->
  <ion-searchbar [debounce]="1000" placeholder="Search" show-clear-button="focus" [(ngModel)]="term" (ngModelChange)="search(term)"></ion-searchbar>
  <ion-list>
    <!-- 直接遍历products数组 -->
    <ion-item *ngFor="let produkt of products | filter : term">
      <ion-label>{{ produkt.product_code }} {{ produkt.name }}</ion-label>
    </ion-item>
  </ion-list>
</ion-content>

2. 修改filter.pipe.ts

export class FilterPipe implements PipeTransform {

  public transform(value: any[], filterText: string) {
    // 先判断value是否存在,不存在返回空数组
    if (!value) return [];
    // 过滤逻辑保留,同时给name添加空值保护
    return filterText.length > 3 
      ? value.filter(x => x?.name?.toLowerCase().includes(filterText.toLowerCase()))
      : value;
  }

}

额外优化建议

  • 避免使用any类型,定义Product接口规范数据类型:
interface Product {
  id: number;
  name: string;
  product_code: string;
}
// 修改products类型:products: Product[] = [];
  • 若term为空时,可根据业务需求清空products或调用API返回全量数据。

内容的提问来源于stack exchange,提问作者weinde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 13:21:24