Angularfire2 - 获取当前用户UID和过滤器列表observable

时间:2016-10-27 08:11:40

标签: angular firebase firebase-realtime-database firebase-authentication angularfire2

如何获取当前用户的UID并使用它来过滤可观察的列表?

我尝试使用const currentUser = this.auth.getAuth()。它返回null并给我一个console.log警告以使用const currentUser = this.auth.subscribe();

当我在console.log中调用currentUser的值时,我得到currentuser: [object Object]

这是我完成的全部功能

showUserProfile() {
    //const currentUser = this.auth.getAuth();
    const currentUser = this.auth.subscribe();
    console.log('currentuser: ' + currentUser);
    return this.af.database.list('/', {
      query: {
          orderByChild: 'useruid',
          equalTo: 'miIMjfVx6TgC9zo6jE0yn0I3JbC2' // currentUser.uid 
      }
    });
  }

在Alexander Ciesielski的帮助下进行第二次尝试

亚历山大建议这样做,但不幸的是它给出了以下错误:Type 'void' is not assignable to type 'FirebaseListObservable<UserProfile[]>'.

 showUserProfile() {
     this.auth.subscribe(authData => {
      console.log(authData);
      let uid = authData.uid;
      return this.af.database.list('/', {
          query: {
              orderByChild: 'useruid',
              equalTo: uid // currentUser.uid 
          }
      });
  });
 } 

我接下来尝试了下面的内容,遗憾的是console.log('the output: ' + output);返回the output: undefined

showUserProfile() {
    let output;
    this.auth.subscribe(authData => {
      const currentUser = authData.uid;
      console.log('Current User ID: ' + currentUser);

       output = this.af.database.list('/', {
          query: {
              orderByChild: 'useruid',
              equalTo: currentUser
          }
        });
    })
    console.log('the output: ' + output);
    return output;
  }

更多信息

showUserProfile方法在另一个组件中调用。

userProfiles: FirebaseListObservable<UserProfile[]>

ngOnInit() {
    this.userProfiles = this.authService.showUserProfile();
    console.log('userprofiles: ' + this.userProfiles);
  }

1 个答案:

答案 0 :(得分:1)

.subscribe()是异步的。

这意味着您需要将callback function作为参数传递给.subscribe()

subscribe()结算时,它会使用实际数据调用callback function,在本例中为auth对象。

userProfiles: FirebaseListObservable<UserProfile[]>

...

this.auth.subscribe(authData => {
    console.log(authData);
    let uid = authData.uid;
    this.userProfiles = this.af.database.list('/', {
        query: {
            orderByChild: 'useruid',
            equalTo: uid // currentUser.uid 
        }
    });
});

必须在回调内设置userProfiles列表。