Issue
I am implementing a search filter function for my ionic app, together with firebase firestore but, the filter does not seem to work. I have been trying a lot of methods but it just does not seem to work. Would appreciate a lot if someone were to help me.. thank you..
Typescript code here
recipeData: any = [];
constructor(private recipeService: RecipeService) {
this.initializeData();
}
initializeData() {
// Getting recipe data from database
this.recipeService.getAllRecipes().subscribe((data)=>{
this.recipeData = data;
});
}
filter(ev : any) {
// Filtering code
this.initializeData();
const val = ev.target.value;
if(val && val.trim() !== ''){
this.recipeData = this.recipeData.filter((item) => {
return(item.Name.toLowerCase().indexOf(val.toLowerCase()) > -1);
});
}
}
HTML code here
<ion-list>
<ion-item *ngFor = "let item of recipeData">
{{item.Name}}
</ion-item>
</ion-list>
Solution
You are calling this.initializeData() from filter method that's the issue.
Every time you call your filter method initializeData method got executed and in initializeData method you are calling to rest api which take time to get data and before rest send the data to your subscribtion of getAllRecipes() code below this.initializeData() in filter method gets execute
const val = ev.target.value;
if(val && val.trim() !== '') {
this.recipeData = this.recipeData.filter((item) => {
return(item.Name.toLowerCase().indexOf(val.toLowerCase()) > -1);
});
and then after subscribe code gets execute
getAllRecipes().subscribe((data) => {
this.recipeData = data;
});
And that the reason you filtered recipeData is again gets the data which comes form rest api.
So the solution here is just this.initializeData() remove this from filter(ev : any) method.
updated filter(ev : any) method given below.
filter(ev : any) {
// Filtering code
const val = ev.target.value;
if(val && val.trim() !== ''){
this.recipeData = this.recipeData.filter((item) => {
return(item.Name.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
Answered By - Vivek Jain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.