使用离子搜索栏过滤离子中的http.get数据

时间:2017-08-03 13:57:30

标签: ionic-framework

在我的Ionic App中,我在家里有以下内容:

export class HomePage {

  itemsInitial = []; //initialize your itemsInitial array empty
  items = []; //initialize your items array empty
  gameTitlesInitial = []; //initialize your itemsInitial array empty
  gameTitles = []; //initialize your items array empty

  searchGameTitleString = ''; // initialize your searchItemsString string empty

  constructor(http: Http) {
    http.get('http://localhost/wordpress-templates/wordpress/index.php/wp-json/wp/v2/business/')
    .map(res => res.json())
    .subscribe(data => {
       this.itemsInitial = data;
       this.items = data;
       var gameTitles = this.items.map(function (el) {
         return el.title.rendered;
       });
       console.log(gameTitles);
    });
  }

  searchGameTitle(searchbar) {
          // reset items list with initial call
          this.gameTitles = this.gameTitlesInitial;
          // set q to the value of the searchbar
          var q = searchbar.target.value;

        // if the value is an empty string don't filter the items
        if (q.trim() == '') {
            return;
        }

      this.gameTitles = this.gameTitles.filter((v) => {
          if (v.toLowerCase().indexOf(q.toLowerCase()) > -1) {
              return true;
          }
          return false;
      })
  }

}

....以及我home.html上的以下内容:

<ion-content>
    <ion-searchbar [(ngModel)]="searchGameTitleString" (input)="searchGameTitle($event)" placeholder="Search"></ion-searchbar>
    <ion-list>
        <button ion-item *ngFor="let gameTitle of gameTitles">
            {{gameTitle}}
        </button>
    </ion-list>
</ion-content>

有人可以帮助我:如何用我的http get中的var“gameTitles”值替换顶部的空数组“gameTitles”?

console.log(gameTitles); 

确实给了我

["game one", "game two", "game three"]
在控制台中

...所以http get似乎有效。

我非常感谢任何帮助 - 我尝试了很多方法但没有成功。

1 个答案:

答案 0 :(得分:1)

经过进一步研究后,这对我有用:

on home.html ...

<ion-content>
  <ion-searchbar (ionInput)="getTitles($event);" [debounce]="500" placeholder="Suchen..." ></ion-searchbar>
  ...
  <ion-list>
    <button ion-item *ngFor="let item of items" (click)="itemTapped($event, item)">
      {{item.title.rendered}}
    </button>
  </ion-list>
</ion-content>

on home.ts ...

this.http.get('someurlhere').map(res => res.json()).subscribe(data => {
  this.posts = data;
  this.initializeItems();
  console.log(this.posts);
  loadingPopup.dismiss();
});

getTitles(ev: any) {
  this.initializeItems();
  // set val to the value of the searchbar
  let val = ev.target.value;
  // if the value is an empty string don't filter the items
  if (val && val.trim() != '') {
    this.items = this.items.filter((item) => {
      return (item.title.rendered.toLowerCase().indexOf(val.toLowerCase()) > -1);
    })
  }
}

initializeItems() {
  console.log('initialized all items');
  this.items = this.posts;
}