0
votes

How do I get the current user UID and use it to filter a list observable?

I tried to use const currentUser = this.auth.getAuth(). It returns null and gives me a console.log warning to use const currentUser = this.auth.subscribe();

When I console.log the value of currentUser, I get currentuser: [object Object] back.

This is the complete function I made

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

second attempt with help from Alexander Ciesielski

Alexander suggested this, but unfortunately it is giving to following error: 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 
          }
      });
  });
 } 

I tried the following next, sadly console.log('the output: ' + output); returns 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;
  }

More information

The showUserProfile method is called in a different component.

userProfiles: FirebaseListObservable<UserProfile[]>

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

1 Answers

1
votes

.subscribe() is asynchronous.

That means you need to pass a callback function as a parameter to .subscribe().

When subscribe() resolves it will call the callback function with the actual data, in this case the auth object.

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

The userProfiles list has to be set from inside the callback.