-1

for some reason I cannot receive the given element value inside the typescript foreach loop

constructor(db: AngularFireDatabase) { 

}
this.fbUserData = this.db.list('users/'+this.userid).valueChanges()
      this.fbUserData.forEach(element => {
        this.currentRole = element[2].toString(); // receive value
    })

now outside the loop I want to receive the value from the AngularFireBase I tried the following:

 this.userid = this.firebaseAuth.auth.currentUser.uid.toString();
      this.fbUserData = this.db.list('users/'+this.userid).valueChanges()
      this.fbUserData.forEach(element => {
          this.rolelist.push(element[2].toString());
    })

but this.rolelist (array) remains empty outside the loop. inside the loop it will receive the value like array ['test']

I want it to console.log outside the loop like this:

   checkAuth(data){


  this.userid = this.firebaseAuth.auth.currentUser.uid.toString();
  this.fbUserData = this.db.list('users/'+this.userid).valueChanges()
  this.fbUserData.forEach(element => {
      this.rolelist.push(element[2].toString());
})
  console.log(this.rolelist);

so that this.rolelist has the element value from the foreach loop

Bcoded
  • 83
  • 10
  • What do you think `this.fbUserData` is? What does your IDE say it is? Once you figure out what it is, what kinds of things can you do with it? What do you think `forEach` is supposed to do? Do you think it's `Array#forEach`, or `FirebaseListObservable#forEach`, which are completely different? By the way, if this is an AngularFire question, please tag it as such, and mention the version you are using. Also, if it's not too much trouble, do yourself and everybody else a big favor and indent your code properly. –  Oct 13 '17 at 17:18
  • You cannot use it outside the subscribe, this is asynchronous, check: https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2 – AT82 Oct 14 '17 at 09:14

1 Answers1

0

Your firebase call returns an Observable => you will have to .subscribe() to this.fbUserData in order to access the value.
this.fbUserData.subscribe(userData => {});
The function inside subscribe will be called every time the data changes with the new data as an argument. If you don't want updates you can do this.fbUserData.first().subscribe(userData => {});.
You might have to import 'rxjs/add/operator/first'; in order for that to work

Isigiel
  • 307
  • 2
  • 12