【问题标题】:Angular TypeError: Cannot read property 'toLowerCase'Angular TypeError:无法读取属性“toLowerCase”
【发布时间】:2021-01-03 16:29:49
【问题描述】:

我正在尝试使用离子搜索栏过滤一组项目,但我的 ts 函数给了我一个错误:

错误类型错误:无法读取属性“toLowerCase”

html代码

<ion-searchbar (ionInput)="function($event)"  showCancelButton="never"></ion-searchbar>
 <div *ngFor="let item of items | async">
  {{item.data.titre}} 
 </div>

打字稿代码

 itemsCollection: AngularFirestoreCollection<Item>;
 items:Observable<any[]>;

ngOnInit(){
      this.itemsCollection=this.fs.collection('Items', ref=>ref.orderBy('Timestamp', 'desc'));
      this.items=this.itemsCollection.snapshotChanges().pipe(
        map(actions => {
          return actions.map(a=>{
            const data=a.payload.doc.data() as Item;
            const id = a.payload.doc.id;
            return{ id, data};
          })
        }));
    }  

function(ev:any){
    this.ngOnInit();
    let val=ev.target.value
    if(val && val.trim()!=''){
    this.items = this.items.filter((item: any) => {
      return (item.titre.toLowerCase().indexOf(val.toLowerCase()) > -1);
    })
    }
  }

我无法修复它,谢谢你帮助我

【问题讨论】:

  • 已经给出了正确的答案,但只是作为一个提示:不要键入任何 lambda 参数。 Typescript 会为您推断它们,如果没有,您将看到该项目没有 toLowerCase 方法。在这件事上,试着摆脱你所有的任何东西——如果你剥夺了正确的打字,那么使用打字稿有什么意义呢?另外,不要将函数命名为 function。这是一个保留的关键字,我很惊讶它甚至可以编译。

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


【解决方案1】:
<div *ngFor="let item of items | async">
  {{item.data.titre}} 
 </div>

您错过了 items 数组的每个对象的 data 属性。

必须是:-

this.items = this.items.filter((item: any) => {
      return (item.data.titre.toLowerCase().indexOf(val.toLowerCase()) > -1);
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-30
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-12
    • 2018-08-07
    相关资源
    最近更新 更多