2017-02-17 3 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); 
    }) 
    } 
} 

Когда я типа в SearchBar я получаю эту ошибку.

enter image description here

+0

Пользователь предполагает, 'item.name' относится к строке. Как вы уверены в этом? – Leon

+0

item.name - это строка, но я не понимаю, как получить доступ к ней в фильтре? – Mohammed

+0

Можете ли вы попробовать объявить 'val' с' let'? то есть '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

Как использовать оператор спреда? Я новичок в угловых 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); 
    }) 
    } 
}