typescript 带有过滤器的搜索栏和带有 Ionic 2 的 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39055621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:46:19  来源:igfitidea点击:

Searchbar with filter and from JSON data with Ionic 2

angulartypescriptionic-frameworkionic2ionic3

提问by olivier

I'm very new to Typescript and Ionic 2 and I'm trying to filter trough a json response with Ionic 2 search bar.

我对 Typescript 和 Ionic 2 非常陌生,我正在尝试使用 Ionic 2 搜索栏过滤 json 响应。

This is my code:

这是我的代码:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';



@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {

  posts: any;
  private searchQuery: string = '';
  private items: string[];
  constructor(private http: Http) {

    this.initializeItems();

    this.http.get('https://domain.co/open.jsonp').map(res => res.json()).subscribe(data => {
        this.posts = data;
        console.log(this.posts);

    });

  }

  initializeItems() {
    this.items = this.posts;
  }

  getItems(ev: any) {
    // Reset items back to all of the items
    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.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  }

}

And the Markup:

和标记:

<ion-header>
  <ion-searchbar (ionInput)="getItems($event)" [debounce]="500" placeholder="Suchen..."></ion-searchbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-item *ngFor="let post of posts">
      <h1>{{post.storeName}}</h1>
    </ion-item>
  </ion-list>
</ion-content>

I this error when I search:

我搜索时出现此错误:

item.toLowerCase is not a function

item.toLowerCase 不是函数

The JSON data looks like this:

JSON 数据如下所示:

[
{
storeName: "Avec Hauptbahnhof",
addressLink: "",
phone: "0326223902",
image: "",
description: "",
link: "",
openingHours: [
"05.30 - 22:00",
"05.30 - 22:00",
"05.30 - 22:00",
"05.30 - 22:00",
"05.30 - 22:00",
"06.30 - 22:00",
"7.00 - 22.00"
]
},
{
storeName: "Manor",
addressLink: "",
phone: "0326258699",
image: "",
customer: "",
description: "",
link: "",
openingHours: [
"09.00 - 18.30",
"09.00 - 18.30",
"09.00 - 18.30",
"09.00 - 21:00",
"09.00 - 18.30",
"08.00 - 17.00",
"Geschlossen"
]
}
]

回答by sebaferreras

You're getting that error because each itemis not a string, but an object, so instead of doing

你得到这个错误是因为每个项目不是一个字符串,而是一个对象,所以而不是做

item.toLowerCase().indexOf(val.toLowerCase()) > -1

You should do

你应该做

item.storeName.toLowerCase().indexOf(val.toLowerCase()) > -1

Also please notice that in your view you're using the postsarray

另请注意,在您看来,您使用的是posts数组

*ngFor="let post of posts" 

But you should use the itemsarray instead, because that's the one that is going to be filtered

但是你应该使用items数组,因为那是要被过滤的数组

  <ion-list>
    <ion-item *ngFor="let item of items">
      <h1>{{item.storeName}}</h1>
    </ion-item>
  </ion-list>


Besides that, I'd do things a little bit different, just to make sure that the user is able to use the page onlywhen the data is available (since you're using an http request to obtain it). In order to do so, I'd add a loading alert and would remove it as soon as the http request is done. As of Ionic2-beta.11, you could do that like this:

除此之外,我会做一些不同的事情,只是为了确保用户只有在数据可用时才能使用该页面(因为您使用的是 http 请求来获取它)。为此,我会添加一个加载警报,并会在 http 请求完成后立即将其删除。从 Ionic2-beta.11 开始,你可以这样做:

import { Component } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';


@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {

  private posts: any; // <- I've added the private keyword 
  private searchQuery: string = '';
  private items: any; // <- items property is now of the same type as posts
  constructor(private http: Http, private loadingCtrl: LoadingController) {

    // this.initializeItems(); <- you don't need this anymore

    // Show the loading message
    let loadingPopup = this.loadingCtrl.create({
      content: 'Loading posts...'
    });

    this.http.get('https://domain.co/open.jsonp').map(res => res.json()).subscribe(data => {
        this.posts = data;
        this.initializeItems();

        // Hide the loading message
        loadingPopup.dismiss();
    });
  }

  initializeItems() {
    this.items = this.posts;
  }

  getItems(ev: any) {
    // Reset items back to all of the items
    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.storeName.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  }

}

回答by Ponmurugan Mohanraj

The same issue I have faced when I worked in angular 2 with ionic.

我在使用 ionic 处理 angular 2 时遇到的同样问题。

In our project, we have one method to get all product list and displayed the items by using *ngFor.

在我们的项目中,我们有一种方法可以使用 *ngFor 获取所有产品列表并显示项目。

Whenever we make search by using ionic search bar, the input search text will be got by using "event.target.value". We have to check if the search text is matched in the items.

每当我们使用 ionic 搜索栏进行搜索时,都会使用“event.target.value”获取输入的搜索文本。我们必须检查搜索文本是否在项目中匹配。

Code is,

代码是,

   getAllProdcuts(isFrom, searchText){
      this.toDoService.getAllProdcuts().then((res) => {
        this.items = res;
            if(isFrom == 'search') {
                this.items = this.items.filter((item) => {
                    return (item.toLowerCase().indexOf(searchText.toLowerCase()) > -1);
                })
            }
        }, (err) => {

        });
    }

  getItems(ev: any) {

    // 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.getAllProdcuts("search", val);
    }
  }

Here, we can get filtered items from the method.

在这里,我们可以从方法中获取过滤的项目。

Thanks.!

谢谢。!