正在尝试在Postpage中创建一些位置数据的搜索选项。但是它给出的错误为“ TypeError:无法读取未定义的属性'toLowerCase'”。在这里添加这些代码。页面文件和相应的服务类已在app.module.ts文件中声明。
<ion-header>
<ion-navbar>
<ion-title>Back</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding text-center>
<ion-title>Search Restaurunt Location</ion-title>
<ion-searchbar [(ngModel)]="searchTerm" (ionInput)="setFilteredItems()"></ion-searchbar>
<ion-list>
<ion-item *ngFor="let data of locationdata">
{{data.name}}
</ion-item>
</ion-list>
</ion-content>
import { Injectable} from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class Data
{
locationdata:any;
constructor()
{
this.locationdata=[
{ "name":"EKM"},
{"name":"CBD"},
{ "name":"KLM"},
{ "name":"KTR"},
{ "name":"CDL"},
];
}
filteritems(searchTerm)
{
return this.locationdata.filter((item) => {
return item.name.toLowerCase().includes(item.searchTerm.toLowerCase());
});
}
}
import { Component ,ViewChild, ElementRef} from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {Data}from './post.service'
declare var google :any;
/**
* Generated class for the PostPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-post',
templateUrl: 'post.html',
})
export class PostPage {
@ViewChild('map')mapref : ElementRef;
map:any;
searchTerm:any;
locationdata:any;
constructor(public navCtrl: NavController, public navParams: NavParams , public data :Data) {
}
ionViewDidLoad() {
// this.showmap();
this.setFilteredItems();
}
setFilteredItems()
{
this.locationdata= this.data.filteritems(this.searchTerm)
}
}
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { PostPage } from './post';
@NgModule({
declarations: [
PostPage,
],
imports: [
IonicPageModule.forChild(PostPage),
],
})
export class PostPageModule {}
答案 0 :(得分:0)
您需要检查item.name
是否未定义,在这里我认为searchterm
对象中不存在item
,它应该来自filteritems函数的参数变量。
filteritems(searchTerm)
{
return this.locationdata.filter((item) => {
if(item.name && searchTerm) {
return item.name.toLowerCase().includes(searchTerm.toLowerCase());
}
});
}
答案 1 :(得分:0)
只需从include方法中删除item参数即可。
filteritems(searchTerm:string)
{
if(searchTerm){
return this.locationdata.filter((item) => {
return item.name.toLowerCase().includes(searchTerm.toLowerCase());
});
}
}
item.searchTerm.toLowerCase()表示您正在尝试访问 item 对象({“名称”: “ EKM”}),因此未定义,然后将toLowerCase()的未定义定义为错误。