【问题标题】:How to match a pipe to a category in a form-group如何将管道与表单组中的类别匹配
【发布时间】:2020-07-13 08:04:58
【问题描述】:

我正在尝试通过在搜索栏中输入一个词来过滤产品,如果类别表单属性与搜索词匹配,则将产品限制为仅该类别。

我可以将所有产品添加到 value 参数中,但我收到一条错误消息,说无法读取未定义的“starts”属性

控制台日志

自定义管道:

if(cName===""){
  return value;
}
else{
  console.log("Value : ",value)
  console.log("cName : ",cName)
const categoryArray:any[]=[];
for(let i=0;i<=value.length;i++){
  let categoryName:string=value[i].category;
  console.log("value i . category ", value[i].category)
  let cName: string = value[i].name;
  if(categoryName.startsWith(cName)){
    categoryArray.push(value[i])
  }
}
return categoryArray;

} }

HTML:

<div style="text-align: center;">
<input type="text" [(ngModel)]="searchCategory">
</div>
<ion-list>
<ion-item *ngFor="let p of products | async |category:searchCategory" [routerLink]="[p.id]">
  <ion-thumbnail slot="start">
    <img [src]="p.img">
  </ion-thumbnail>
  <ion-label>
    {{ p.name }}
    <p>{{ p.price | currency:'USD' }}</p>
  </ion-label>
</ion-item>

ts:

products: Observable<any>;
searchCategory:string="";

和 ngOnInit:

ngOnInit() {
this.products = this.productService.getAllProducts();
console.log("all products", this.products);
}

编辑: 按照 Shubham Bhokare 的建议删除类别的空条目后,我在控制台中遇到了新错误:

console logs 2

【问题讨论】:

  • 您附上了与上面相同的错误日志图像。请提供另一个错误日志。

标签: angular typescript ionic-framework google-cloud-firestore angular-pipe


【解决方案1】:

"" 类别中有一些空条目。

因此,let categoryName:string=value[i].category 这条语句将 categoryName 存储为 undefined,因为 value[i].category 中没有任何值。

由于上述问题,此检查条件if(categoryName.startsWith(cName)) 失败。

通过 if(categoryName &amp;&amp; categoryName.startsWith(cName)) 处理未定义的值。

【讨论】:

  • 好的,我删除了 firebase 中类别的空条目并进行了更改以处理未定义。现在错误显示“无法读取未定义的属性“类别”。在控制台中记录其打印产品类别但不过滤
  • @cononor96,您的 for 循环现在正在创建错误,它应该是 for(let i=0;i&lt;value.length;i++)。删除“=”。
猜你喜欢
  • 1970-01-01
  • 2014-09-28
  • 1970-01-01
  • 2015-09-24
  • 1970-01-01
  • 2015-07-24
  • 2023-04-04
  • 1970-01-01
  • 2021-10-22
相关资源
最近更新 更多