【问题标题】:Filter not working in angular?过滤器不工作在角度?
【发布时间】:2017-12-20 22:46:12
【问题描述】:

我有一个从 firebase 接收的简单数据,但过滤器不适用于该数据。 我搜索了很多帖子,但没有任何帮助。 缺少什么。?任何帮助

如果它在 OnInit() 中,我可以实现相同的数据。 以下是我的代码:

export class SignUpComponent implements OnInit {
ngOnInit() {
const someEvemnts = [
{type: 'attack', value: 1, target: 'dorkman'},
{type: 'yaeed', value: 2, target: 'dorkman'},
{type: 'attack', value: 3, target: 'fluffy'},
{type: 'attack', value: 4, target: 'dorkman'},
]
const total = someEvemnts
 .filter(event => event.type== 'attack')
 .filter(event => event.target== 'dorkman')
console.log(total); // works fine 

let check = this.values; // works fine 
let check2 = this.values.filter(val => val) // not works 
console.log(check);
console.log(check2); // returns empty
this.SignIn();
}

SignIn(){
  firebase.database().ref('/companies').on('child_added', (data)=>{
      this.values.push(data.val())
  }
  )
}
values=[];
}

控制台:

.

【问题讨论】:

    标签: javascript angular firebase firebase-realtime-database


    【解决方案1】:

    它不起作用,因为你调用 this.SignIn();在调用 console.log 后填充“Values”变量。因此,当您进行控制台时,“值”为空。

    变量流行后执行“console.log”。

    试试这个:

    export class SignUpComponent implements OnInit {
    ngOnInit() {
    const someEvemnts = [
    {type: 'attack', value: 1, target: 'dorkman'},
    {type: 'yaeed', value: 2, target: 'dorkman'},
    {type: 'attack', value: 3, target: 'fluffy'},
    {type: 'attack', value: 4, target: 'dorkman'},
    ]
    const total = someEvemnts
     .filter(event => event.type== 'attack')
     .filter(event => event.target== 'dorkman')
    console.log(total); // works fine 
    
    this.SignIn();
    }
    
    SignIn(){
      firebase.database().ref('/companies').on('child_added', (data)=>{
          this.values.push(data.val())
    
          let check = this.values; // works fine 
          let check2 = this.values.filter(val => val) // not works 
          console.log(check);
          console.log(check2); // returns empty
      }
      )
    }
    values=[];
    }
    

    【讨论】:

    • 正确的要么将其放入数据库的响应中,要么可以在触发不同功能的 html 事件之后进行过滤。
    • 但首先我想将数据推送到值,然后只有我想访问该数据。
    【解决方案2】:
    let check2 = this.values.filter(val => val) // not works
    

    不做这样的表达是不行的

    let check2 = this.values.filter(val => val.isAwesome)
    

    您要过滤什么?如果你想过滤字符串,你喜欢:

    let check2 = this.values.filter(val => val.label === 'hello')
    

    【讨论】:

    • 这就是我想要达到的目标,但没有按预期工作
    • 您要过滤哪个变量?您的数据中没有布尔值。您的代码过滤了整个对象,无法过滤,因此它什么也不返回。
    • 让 check2 = this.values.filter(val => val.name == 'shanth')
    猜你喜欢
    • 1970-01-01
    • 2018-11-18
    • 2023-04-03
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    相关资源
    最近更新 更多