如何从角度6的Firebase实时数据库中基于密钥获取单个记录

时间:2018-08-14 07:26:04

标签: javascript angular firebase firebase-realtime-database angular2-forms

我正在尝试从Firebase数据库中获取单条记录数据,但是我无法从Firebase中获取单条记录数据。

我能够将记录添加到firebase中,并且能够获取并显示列表中的所有记录。

我正在尝试根据$key

获得单条记录

我上传了db json enter image description here

我的依赖项

enter image description here

我的详细信息页面组件

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { UserService } from '../user.service';

 @Component({
 selector: 'app-user-details',
 templateUrl: './user-details.component.html',
 styleUrls: ['./user-details.component.css']
 })
 export class UserDetailsComponent implements OnInit {

 id: any;
 userList: any;
 imageUrl: any;

 constructor(private _user: UserService, private router: Router, private 
 arouter: ActivatedRoute) { }

ngOnInit() {
 this.id = this.arouter.snapshot.params['id'];
 console.log(this.id);
 this._user.getUserDetails(this.id)
 .subscribe(res => {
  this.userList = res;
 });
 console.log(this.userList);
 }

}

我的服务文件:

import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList, FirebaseObjectObservable } 
 from 'angularfire2/database';
import { User } from './user';
import * as firebase from 'firebase';

@Injectable({
 providedIn: 'root'
})
export class UserService {

 userList:  AngularFireList<User>;
 folder: any;
 userDetails: AngularFireList<User>;

 constructor(private _fb: AngularFireDatabase) {
  this.folder = 'userProfile';
  this.userList = _fb.list('/user');
 }

 getAllUser() {
  return this.userList;
 }

 inserUser(contFrm: User){
  this.userList.push(contFrm);
 }

 getUserDetails(id) {
  this.userDetails = this._fb.list('/user'ref => ref.equalTo(id)).valueChanges());

  return this.userDetails;
  }

它不会引发任何错误,但是我无法获取记录数据。

1 个答案:

答案 0 :(得分:0)

从AngularFireList 5.0版开始,您必须在valueChanges之后链接list以返回Observable 此外,您没有在getUserDetails方法

中返回值
getUserDetails(id) {
  this.userDetails = this._fb.list('/user', {
    query: {
      orderByChild: 'fname',
      equalTo: id
    }
  }).valueChanges();

  return this.userDetails;
}