我正在尝试使用 angular 过滤来自 firebase 数据库的数据。但它不断出现这样的错误 - 错误类型错误:无法读取未定义的属性“toLowerCase”。有人可以帮助我吗?以下是我在 search.ts 中的功能
searchuser(searchbar) {
this.filteredusers = this.temparr;
var q = searchbar.target.value;
if (q.trim() == '') {
return;
}
this.filteredusers = this.filteredusers.filter((v) => {
if (v.displayName.toLowerCase().indexOf(q.toLowerCase()) > -1 || v.subject.toLowerCase().indexOf(q.toLowerCase()) > -1) {
return true;
}
return false;
})}
下面是我的html代码
<ion-content padding>
<ion-searchbar [(ngModel)]="searchstring" (input)="searchuser($event)" placeholder="Search"></ion-searchbar>
<ion-list no-lines>
<ion-list>
<ion-item-sliding *ngFor="let key of filteredusers" >
<ion-item >
<ion-avatar item-left>
<img src="{{key.photoURL}}">
</ion-avatar>
<h2>{{key.displayName}} </h2>
<p>Rate/Hour:RM{{key.rate}}</p>
<p>Subject:{{key.subject}}</p>
<p>Distance:0.5KM</p>
</ion-item>
<ion-item-options slide="left">
<button ion-button color="primary" (click)="call(key)">
<ion-icon name="call"></ion-icon>
Call
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-list>
</ion-content>
我期望的过滤结果是搜索功能可以从数据库中过滤名称和主题。
最佳答案
将您的条件检查更新为:
if (v.displayName && v.displayName.toLowerCase()...
如果您尝试调用方法(在本例中为 toLowerCase
)或访问 null
或 undefined
上的属性,您通常会遇到该错误> 对象。这本质上是 Javascript 版本的空引用异常
。
通过检查 v.displayName
,您可以确保 displayName
属性存在于您的对象 v
中,并且它的值不是 undefined
或 null
。
如果 displayName
属性可能是除 string
之外的任何类型,那么在调用 toLowerCase 之前对属性进行类型检查可能也会受益
就可以了。您可以使用 typeof v.displayName === "string"
进行类型检查。因此,更完整的检查是:
if (v.displayName && typeof v.displayName === "string" && v.displayName.toLowerCase()...
关于javascript - 错误类型错误 : Cannot read property 'toLowerCase' of undefined. Ionic 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47659665/