过滤器不工作角度?

时间:2017-12-20 10:38:21

标签: javascript angular firebase firebase-realtime-database

我有一个从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=[];
}

控制台:

console

2 个答案:

答案 0 :(得分: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=[];
}

答案 1 :(得分:0)

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')