Ion-searchbar in real time with database


#1

Hi !
How Can I interact with my database in real time when the user enter letter in ion-searchbar please ?


#2

Start with a behavior subject to act as search terms. Create a function to implement next on that behavior subject. Continuously match strings based on information in your database. Send out an Observable of matching terms. Subscribe.


#3

But with this solution, the server will receive many request ?! Is it good for him ?


#4

Probably not. But do you really expect a searchbar in “real time” to be especially efficient? That’s about as likely as @rapropos’ cat growing a mullet. Probably not gonna happen.

Get your data on the front end and store it if you’re seriously concerned about performance I suppose.


#5

Ok thank you very much !


#6

To store the data in local is depends on the size of your data.
If you have more than 100 items i suggest you to make your searchbar as server side autocomplete


#7

But how I can do that please ? I would like something like facebook where when you tap, the result appear in real time…


#8

html file:

 <ion-searchbar #searchBarEl
                 [(ngModel)]="query"
                 (ionInput)="getResults()">
  </ion-searchbar>

  <ion-list *ngIf="matches.length > 0">
    <ng-container *ngFor="let item of matches">

      <ion-item [style.height]="40"  (click)="selectItem(item)" role="button">
        <div>{{item.description}}</div>
      </ion-item>

    </ng-container>

  </ion-list>

ts file:

...
getResults() {
   this.matches = [];
    this.selected = {
      id: '',
      description: ''
    };

    this.loadingMatches = true;

    this.apiProvider.get('serverUrl', {query: this.query}).then((res:any) => {
      this.loadingMatches = false;

      this.matches = res;
    }, (err) => {
      this.loadingMatches = false;
      console.log('err: ', err);
    });
}

...

#9

Thanks I will try ! :slight_smile:


#10

I try and that’s work ! But just one question please. Why did you put $event in this “getResults($event)” ?


#11

You pass the searchbar value in $event


#12

But we have already this information with the doubl binding in ngModel ?


#13

You can use the ngModel variable.
If you want you can call to “getResults()” without $event it will work.