【问题标题】:how to get firebase document as a angular object model如何将firebase文档作为角度对象模型
【发布时间】:2019-09-10 07:37:12
【问题描述】:

我将firebase用户配置文件数据文档ID保存为用户ID,现在我想使用当前记录的用户ID从firebase用户集合中获取当前记录的用户数据并将其转换为角度模型对象我尝试了一些方法,但这些方法给了我错误.

首先我使用下面的代码获取我当前登录的用户 ID

this.afAuth.auth.onAuthStateChanged(user => {
    if (user) {
    this.selectedid = user.uid;

在我创建用户对象并最终将其分配给 firebase 文档数据后,如下所示

getnannies() {
    return this.db.collection('nanny').doc(this.selectedid).valueChanges() 
    as Nanny;
}

(保姆是我的模型类的类型) 然后我尝试按如下方式访问该文档数据

nanny:Nanny;
this.nanny = this.serviceClass.getnannies();
console.log(this.nanny.name);

但是这种方法给了我错误,我想知道如何做到这一点。我的完整代码附在下面

这是我的服务文件

export class GetNannyDetailsService {
selectedid: string;
constructor(private db: AngularFirestore, private afAuth: AngularFireAuth, 
private router: Router) {
}

  parseNanny() {
    this.afAuth.auth.onAuthStateChanged(user => {
      if (user) {
        this.selectedid = user.uid;}});
  }
getnannies() {
    return this.db.collection('nanny').doc(this.selectedid).valueChanges() 
as Nanny;
}

这是我的 profile.component.ts

export class ProfileComponent implements OnInit {
pronan:Nanny;
constructor(private profile: GetNannyDetailsService) {
}
ngOnInit() {
    this.profile.parseNanny();
    this.pronan = this.profile.getnannies();
    console.log(this.pronan.name);}

这是我的保姆模特

export interface Nanny {
  email?: string;
  password?: string;
  nannyId?: string;
  name?: string;
  address?: string;
  number?: string;
  gender ?: string;
  town?: string;
  jobType ?: string;
  birthdate?: Date;
  hourlyRate?: number;
  availability?: string;
  bio?: string;
  imgurl?: string;
}

最后控制台显示“未定义”请帮助我。

【问题讨论】:

  • 你能发布错误吗?

标签: angular firebase google-cloud-firestore


【解决方案1】:

在服务文件中使用一个功能。

getNanny() {
        let s: Subject<Nany> = new Subject();
            this.afAuth.auth.onAuthStateChanged(user => {
              if (user) {

                  this.db.collection('nanny').doc(user.id).get().subscribe(
                      next => {
                      s.next(next.data())
                      });
               }
            });
            return return s as Observable<Nany>
        }

在组件文件中,通过订阅服务方法获取对象。

pronan:Nanny;
constructor(private profile: GetNannyDetailsService) {
}
ngOnInit() {

    this.profile.getnannies().subscribe(nany=>{
    this.pronan=nany
    consple.log(nany)
    });
}

【讨论】:

猜你喜欢
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多