首页 > 解决方案 > 将变量传递给firestore where查询(Angular)

问题描述

我正在尝试查询计划集合,其中文档中的字段 = 用户 ID,但我收到此错误:“函数 Query.where() 需要有效的第三个参数,但它未定义。”

     userId;
     uid;
     sched: Observable<ScheduleModel[]>;

ngOnInit()

  ngOnInit() {
    this.userId = this.afAuth.authState.subscribe(user => {
      this.uid = user.uid;
    });
    this.getSched();
  }
getSched() {
  this.sched = this.afs.collectionGroup<ScheduleModel>('schedule', ref => ref.where('uid', '==', this.uid)).valueChanges();
}

查询中的 this.uid 给我带来了麻烦,但是:

  1. 当我输入实际用户 uid 'iq6DkETjgMSMIdxw9cvLEzbf9Fr2' 而不是 this.uid 时,它可以工作。
  2. 在我的模板文件中,当我使用 {{ uid }} 并打印正确的 id 时,它实际上并不是未定义的。

标签: angulartypescriptfirebase

解决方案


尝试这个

ngOnInit() {
let self = this;
this.userId = this.afAuth.authState.subscribe(user => {
  self.uid = user.uid;
});
this.getSched();
}

this在您this.uid的范围内与您使用的范围不同{{uid}}


推荐阅读