Retrieving user profile data from firebase and displaying

Im creating user profile in firebase with this code:

username: string
msgnumber: number
level: number

constructor(private fire:AngularFireAuth,private db :AngularFireDatabase,public navCtrl: NavController, public navParams: NavParams) {

}

createProfile() {

    this.fire.authState.take(1).subscribe(auth => {

    this.db.object(`profile/${auth.uid}`).set({
        username: this.username,
        msgnumber: 0,
        level: 0
    }).then(() => 
        this.navCtrl.setRoot(TabsPage));
    })
}

It is working. Now I'm trying to take the data of user and display it on their profile page.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {AngularFireAuth} from 'angularfire2/auth';
import {AngularFireDatabase,FirebaseListObservable} from 'angularfire2/database';


@Component({
    selector: 'page-profile',
    templateUrl: 'profile.html'
})

export class ProfilePage {
    profileData: FirebaseListObservable<any>

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

        this.fire.authState.subscribe(auth =>{
            this.profileData = this.db.list(`profile/${auth.uid}`);
            console.log(this.profileData);
        });
    }
}

I tried something like this but looks like it's not working. The problem is I guess I couldn't get the idea of object/list observables or generally how to retrieve data and how object observables are working. Checked internet and I guess people are using them to retrieve data?

database: db

Upvotes: 2

Views: 1096

Answers (1)

Orlandster
Orlandster

Reputation: 4858

You're on the right way. To finally retrieve the data you need to subscribe to the second observable which is assigned to this.profileData.

Like this:

this.fire.authState.subscribe(auth => {
  // subscribe to the observable
  this.db.list(`profile/${auth.uid}`).valueChanges().subscribe(profile => {
    console.log(profile);
  });
});

Now to avoid the nesting you can make use of the switchMap operator which rxjs offers you.

The result looks like this:

this.profileData$ = this.fire.authState.switchMap(auth => this.db.list(`profile/${auth.uid}`).valueChanges());
this.profileData$.subscribe(profile => console.log(profile))

Upvotes: 1

Related Questions