以角度2打字稿过滤数组

时间:2017-02-17 10:11:22

标签: angular typescript ionic2

我正在研究如何使用typescript过滤带有Angular 2中数据的数组。过滤是针对Ionic 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

2 个答案:

答案 0 :(得分:2)

我找到了解决方案。

  1. 将键更改为对象中的字符串
  2. 在return语句
  3. 中添加了[0]
  4. 将数组更改为orginames并设置items = orginames,这样可确保在搜索并再次删除单词时数组不会为空。
  5. 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);
        })
      }
    }
    

答案 1 :(得分: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
    }
  );