Reputation: 13
I'm trying to get one record by uid from my firebase database in Angular 2 app. The problem is that I'm always getting undefinied
in profile variable. Could you show me correct way to do this? Thanks!
My code:
Profile class
export class Profile{
constructor(public $key:string, public userId:string, public description:string, public avatarUrl: string){
}
static parseFromJson({$key, userId, description, avatarUrl}):Profile{
return new Profile($key, userId, description, avatarUrl);
}
}
Profiles service
@Injectable()
export class ProfilesService {
constructor(private db: AngularFireDatabase) {
}
getUserByUserId(userId:string): Observable<Profile>{
return this.db.list('profiles',{
query: {
orderByChild: 'userId',
equalTo: userId
}
}).map(result => Profile.parseFromJson(result[0]));
}
}
Profile component
export class ProfileComponent {
profile: Profile;
uid: string;
constructor(private profileService: ProfilesService, private af: AngularFire) {
this.af.auth.subscribe(auth => this.uid = auth.uid);
this.profileService.getUserByUserId(this.uid).subscribe(
result => {
this.profile = result;
}
);
}
}
Upvotes: 1
Views: 1692
Reputation: 1
The result is an array, you might want to take the first value and return as Observable
.
.first
emits only the first value (or the first value that meets some condition) emitted by the sourceObservable
.
getUserByUserId(userId:string): Observable<Profile>{
return this.db.list('profiles',{
query: {
orderByChild: 'userId',
equalTo: userId
}
})
.first()
.map(result => Profile.parseFromJson(result));
Upvotes: 2