The search is not running normally

export class HomePage {
  searchQuery: string = '';
  constructor(public navCtrl: NavController, public loadingCtrl: LoadingController, private toastCtrl: ToastController, public authService: AuthService) {
    this.initializeItems();
  }

  initializeItems() {
    this.authService.loker().then((result) => {
      this.items = result;
    }, (err) => {
      this.presentToast(err);
    });
  }

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

  doRefresh(refresher) {
    setTimeout(() => {
      this.initializeItems();
      refresher.complete();
    }, 2000);
  }

after filling the keyword in the search form, the results of the keyword entered in the show but suddenly re-show again the normal data.

In getItems, you need to wait for initializeItems to finish before filtering.

Hi sigmund, can you help me give me example ?

Sure. I’m no longer on my phone so I can be less brief.

The issue is that you call initializeItems, and that grabs data via a promise.
So what happens is you start to load items, you filter them, and then loading completes and changes your items.

So I’d do the following, first, change initializeItems to:

initializeItems() {
  return this.authService.loker().then((result) => {
    this.items = result;
  }, (err) => {
    this.presentToast(err);
  });
}

Then update getItems to:

getItems(ev: any) {
  this.initializeItems().then(_ => {
    let val = ev.target.value;
    if (val && val.trim() != '') {
      this.items = this.items.filter((item) => {
        return (item.title.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  });
}

This will wait for items to be initialized before filtering them.

1 Like