根据if条件过滤Observable数组

时间:2018-01-13 13:43:01

标签: angular rxjs observable

我从API的get调用中收到一个元素流,在第一次执行此操作时,我不需要过滤此数据。我可以提供信息。

但是根据有人可以选择的过滤器,我有一个表单,我需要过滤数据。

我遇到的主要问题是我使用map运算符迭代数组中的所有元素,并且当它与filter.continent具有相同的大陆时返回此国家但是当它不匹配时返回undefined。< / p>

然后经过这个过滤器,我得到这样的东西:

[undefined, {some country data}, undefined, undefined, {some country data}]

这是我的重新过滤函数的代码示例

refilterValues(){
    Observable.from(this.data)
    .map((country)=>{
      if(this.filters.continent == "All"){
        return country;
      }else{
        if(country["continent"] == this.filters.continent){
          console.log(country)

          return country
        }
      }
    })
}

1 个答案:

答案 0 :(得分:2)

您应该使用过滤器operator而不是map运算符。 Map迭代所有元素并返回一些东西,即使你的逻辑没有返回任何东西(因为它出现在你的数组中的undefined)。过滤器获取可观察的输出,并且只有在逻辑返回true时才返回它。

  

过滤源Observable发出的项目   满足指定的谓词。

refilterValues(){
  Observable.from(this.data)
    .filter((country)=>{
      if(this.filters.continent == "All"){
        return true;
      }else{
        if(country["continent"] == this.filters.continent){
         console.log(country)

        return true
      }
      return false
    }
  })
}
相关问题