Get firebase database of current uid returns undef

2019-08-19 10:41发布

问题:

I have a page to a retrieve user's information, but I am getting undefined.

Below is my data structure

{
  "posts" : {
    "-L4QKxs6d06Vq3amQ7C8" : {
      "content" : "Test",
      "owner" : "D5hkgRIN87OUr3rdSGK1Znws1aB2",
      "title" : "Admin Post"
    },
    "-L4UDg1_glHcqwGjGpTQ" : {
      "content" : "fsdfd",
      "owner" : "D5hkgRIN87OUr3rdSGK1Znws1aB2",
      "title" : "rewsrwr"
    }
  },
  "users" : {
    "D5hkgRIN87OUr3rdSGK1Znws1aB2" : {
      "posts" : {
        "-L4QKxs6d06Vq3amQ7C8" : {
          "title" : "Admin post"
        },
        "-L4UDg1_glHcqwGjGpTQ" : {
          "title" : "rewsrwr"
        },
        "-L4UDj1vKnTpogjZ26Zg" : {
          "title" : "sdfsdf"
        }
      },
      "role" : "0",
      "username" : "Admin"
    }
  }
}

profile.ts

export class ProfilePage {
  currentUser = firebase.auth().currentUser;
  user: Observable<User[]>;

  constructor(public navCtrl: NavController, private db: AngularFireDatabase) {
    this.user = this.db.list(`/users/${this.currentUser.uid}`).snapshotChanges()
    .map(actions => {
      return actions.map(action => {
        return { key: action.key, ...action.payload.val() };
      });
    });
    console.log(this.user.username);
  }

}
  • "angularfire2": "5.0.0-rc.4",
  • "firebase": "4.8.2",

Am I doing something wrong here?

回答1:

Try changing the

.map(actions => {
return actions.map(action => ({
  key: action.key, ...action.payload.val()
}));

part to

.map(actions => {
return actions.map(action => {
  return { key: action.key, ...action.payload.val() };
});


回答2:

import { AngularFireAuth } from 'angularfire2/auth';

export class ProfilePage {

  user: Observable<User>;

  constructor(public navCtrl: NavController, private db: AngularFireDatabase, private afAuth:AngularFireAuth) {

  }

  ngOnInit() {
      //get current user
        this.afAuth.authState.map((auth) =>  {
        if(auth != null) {
            this.user = this.db.list(`/users/${auth.uid}`).snapshotChanges()
            .map(actions => {
                return actions.map(action => {
                    return { key: action.key, ...action.payload.val() };
                });
            });
            this.user.subscribe(user=>{
                console.log(user.username);
            }
        } else {
            console.log('error getting user...')
        }
        }).subscribe();
  }

}

Or you can use it in your template without subscribe

<pre>{{(user | async)?.username}}</pre>


回答3:

I finally figured it out! took some hints from angularfire2 issue#396

profile.ts

export class ProfilePage {
  currentUser = firebase.auth().currentUser;
  user: any;

  constructor(public navCtrl: NavController, private db: AngularFireDatabase) {
    this.db.list(`/users/${this.currentUser.uid}`).snapshotChanges().subscribe(user => {
      this.user = user.payload.val();
  }
    console.log(this.user.username);
  }