如何将firebase文档作为角度对象模型

问题描述 投票:0回答:1

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

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

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

在我创建User对象之后,最后将其分配给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个回答
0
投票

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

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)
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.