angular 搜索栏 this.items.filter 不是函数

angular search bar this.items.filter is not a function

我正在从本地存储的 JSON 文件中获取数据。JSON 字符串是位置城市名称的数组。

{
    "data": [
      {
        "city": {
          "cityname": {
            "id": "الموصل"
          },
          "coords": {
            "long": 43.129,
            "lat": 36.342
          }
        }
      },
          {
        "city": {
          "cityname": {
            "id": "بغداد"
          },
          "coords": {
            "long": 43.129,
            "lat": 36.342
          }
        }
      }

    ]
  }

我在 html 中有回复。并且所有数据数组都在显示,但是当我在框搜索中搜索任何城市名称时出现错误:

 ERROR TypeError: this.items.filter is not a function
    at Tab1Page.push../src/app/tab1/tab1.page.ts.Tab1Page.getItems (tab1.page.ts:74)
    at Object.eval [as handleEvent] (Tab1Page.html:35)
    at handleEvent (core.js:23106)
    at callWithDebugContext (core.js:24176)
    at Object.debugHandleEvent [as handleEvent] (core.js:23903)
    at dispatchEvent (core.js:20555)
    at core.js:21002
    at HTMLElement.<anonymous> (platform-browser.js:993)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17289)

代码:

 items:any


constructor() {

    this.initializeItems()

}

initializeItems() {


  this.items ={
    "data": [
      {
        "city": {
          "cityname": {
            "id": "الموصل"
          },
          "coords": {
            "long": 43.129,
            "lat": 36.342
          }
        }
      },
          {
        "city": {
          "cityname": {
            "id": "بغداد"
          },
          "coords": {
            "long": 43.129,
            "lat": 36.342
          }
        }
      }

    ]
  }
}


getItems(ev: any) {
  // Reset items back to all of the items
  this.initializeItems();

  // set val to the value of the searchbar
  const 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) => {
      item["data"].city.cityname.id.toLowerCase().indexOf(val.toLowerCase()) > -1
      console.log(item)
    })
  }
}

Html

  <ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
  <ion-list>

    <ion-item *ngFor="let item of items.data">
      {{ item.city.cityname.id}}
    </ion-item>
  </ion-list>

有什么想法吗?

你应该改变:

this.items.filter

至:

this.items.data.filter

因为 this.itemsJSON 对象和过滤器函数需要过滤数组

WORKING DEMO(过滤功能bug解决)

在您的 getItems 函数中

this.items.filter((item) => { 应该是

this.items.data.filter((item) => {

因为过滤器需要一个数组。