Reputation: 206
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);
}
}
Am I doing something wrong here?
Upvotes: 1
Views: 934
Reputation: 206
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);
}
Upvotes: 0
Reputation: 6900
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>
Upvotes: 1
Reputation: 5928
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() };
});
Upvotes: 1