2017-02-17 57 views
1

我正在研究如何用打字稿過濾帶Angular 2中數據的數組。過濾是針對Ionic 2中的搜索欄,模板中的列表正在獲取數據並顯示,但過濾不起作用。在角度2打字稿中過濾數組

initializeItems(i:number) { 
this.http.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+this.placeid+'&key=AIzaSyBPi-ayuvkTht4wddCcvcy0l2wIBdT9P2w').map(res => res.json()).subscribe(data => { 
    this.locations[i]._detail = data.result; 

    this.names.push([ 
    { 
     name: this.locations[i]._detail.name, 
     adress: this.locations[i]._detail.formatted_address, 
     phone: this.locations[i]._detail.formatted_phone_number 
    } 
    ]); 

    this.items = this.names; 
    console.log(this.items); 
}); 
} 

getItems(ev) { 
    this.items = this.names; 
    console.log(this.items); 
    // set val to the value of the ev target 
    var 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.name.toLowerCase().indexOf(val.toLowerCase()) > -1); 
    }) 
    } 
} 

當我在搜索欄鍵入我得到這個錯誤。

enter image description here

+0

用戶被假定'item.name'指字符串。你對此有多確定? – Leon

+0

item.name是一個字符串,但我不知道如何在過濾器中訪問它? – Mohammed

+0

你可以嘗試用'let'聲明'val'嗎?即'let val = ev.target.value;' – AngularChef

回答

0

我想你申請push錯誤。將對象推入數組而不是另一個數組。如果您有多個名稱,請使用spread運營商

this.names.push(
    { 
     name: this.locations[i]._detail.name, 
     adress: this.locations[i]._detail.formatted_address, 
     phone: this.locations[i]._detail.formatted_phone_number 
    } 
); 
+0

我該如何使用spread運算符?我是新的角2和打字稿。 – Mohammed

+0

您是否嘗試過上述更改?這應該工作。 – raj

+0

瞭解傳播運營商簽出此文檔。有了這個,你可以將數組的所有元素推送到另一個數組'array.push(... anotherArray)''。它是一個JS運算符。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator – raj

2

我找到了解決方案。

  1. 改變了鍵爲字符串對象中的
  2. 加入[0]中返回語句
  3. 陣列改爲orginames並設定項目= orginames,這確保了該陣列將不會是空的,如果你搜索並再次刪除該單詞。

initializeItems(i:number) { 
this.http.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+this.placeid+'&key=AIzaSyBPi-ayuvkTht4wddCcvcy0l2wIBdT9P2w').map(res => res.json()).subscribe(data => { 
    this.locations[i]._detail = data.result; 


    this.orginames.push([ 
    { 
     "name": this.locations[i]._detail.name, 
     "adress": this.locations[i]._detail.formatted_address, 
     "phone": this.locations[i]._detail.formatted_phone_number 
    } 
    ]); 

    this.items = this.orginames; 
    // this.orginames.push(this.locations[i]._detail.name); 

}); 
console.log(this.items); 

} 

getItems(ev) { 
    this.items = this.orginames; 
    //console.log(this.items); 
    // set val to the value of the ev target 
    var 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[0].name.toLowerCase().indexOf(val.toLowerCase()) > -1); 
    }) 
    } 
}