获取当前uid的firebase数据库返回undefined

时间:2018-02-06 17:06:41

标签: firebase ionic-framework firebase-realtime-database angularfire2

我有一个页面来检索用户的信息,但我没有定义。

以下是我的数据结构

{
  "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);
  }

}
  • &#34; angularfire2&#34;:&#34; 5.0.0-rc.4&#34;,
  • &#34; firebase&#34;:&#34; 4.8.2&#34;,

我在这里做错了吗?

3 个答案:

答案 0 :(得分:1)

尝试更改

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

部分到

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

答案 1 :(得分:1)

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();
  }

}

或者您可以在没有订阅的模板中使用它

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

答案 2 :(得分:0)

我终于明白了!从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);
  }