Как получить одну запись с firebase в Angular 2
Я пытаюсь получить одну запись по uid из моей базы данных Firebase в приложении Angular 2. Проблема в том, что я всегда получаю undefinied
в переменной профиля. Не могли бы вы показать мне правильный способ сделать это? Спасибо! Мой код:
Профиль класса
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);
}
}
Сервис профилей
@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]));
}
}
Компонент профиля
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;
}
);
}
}
1 ответ
Решение
Результатом является массив, вы можете принять первое значение и вернуть как Observable
,
.first
испускает только первое значение (или первое значение, которое удовлетворяет некоторому условию), выданное источникомObservable
,
getUserByUserId(userId:string): Observable<Profile>{
return this.db.list('profiles',{
query: {
orderByChild: 'userId',
equalTo: userId
}
})
.first()
.map(result => Profile.parseFromJson(result));