【问题标题】:ID dynamic document firestoreID 动态文档 Firestore
【发布时间】:2018-09-22 22:46:27
【问题描述】:

如何使firestore QEoevSjHlswgk44nVTsr中的这个文档的ID动态化,即根据该集合中的ID改变?我正在使用 angularfire2:^5.0.0-rc.11

这就是我所拥有的:

firebase.service.ts

proyectos: Observable<Proyecto[]>;

getImagenDestacada() {
    this.proyectos = this.afs.collection('proyectos').doc('QEoevSjHlswgk44nVTsr').collection('archivos', ref => ref
    .orderBy('nombre','asc').limit(1)
    ).snapshotChanges().pipe(map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Proyecto;
        const id = a.payload.doc.id; 
        return { id, ...data };
      });
    }));
    return this.proyectos
    }

=========================

我尝试了以下方法:

firebase.service.ts

getImagenDestacada(id:string) {
this.proyectos = this.afs.collection('proyectos').doc(id).collection('archivos', ref => ref
.orderBy('nombre','asc').limit(1)
).snapshotChanges().pipe(map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data() as Proyecto;
    const id = a.payload.doc.id; 
    return { id, ...data };
  });
}));
return this.proyectos
}

portafolio.component.ts

archivos: Observable<Proyecto[]>;

this.archivos = this.fs.getImagenDestacada(this.id);

但我收到以下错误:

错误:函数 CollectionReference.doc() 要求其第一个参数为字符串类型,但它是:未定义

【问题讨论】:

  • 错误告诉您this.id 未定义。确保在调用 getImagenDestacada() 之前将其设置为字符串。
  • 我将 id 设置为字符串 id: string 我实际上可以访问集合的 ID proyectos 我可以在控制台中打印它们,但我不知道如何为 @ 定义它987654329@会不会是因为是子集合?
  • id: string 只是意味着您正在创建一个期望保存字符串的变量。和id: string = undefined;一样。
  • 你有什么参考或例子可以让我更好地理解这一点吗?我会很感激的。
  • 你在 portafolio.component.ts 中将this.id 设置在哪里?

标签: angular firebase google-cloud-firestore angularfire2


【解决方案1】:

试试这个:const id = a.payload.doc.id.toString();

【讨论】:

    【解决方案2】:

    错误是因为当你调用

    this.proyectos = this.afs.collection('proyectos').doc(id).collection ...
    

    id 未定义,因为 this.id 在调用者中未定义。

    根据the Firebase documentation,如果你想要一个动态生成的id,那么你可以简单地将参数留空,即。将该行更改为:

    this.proyectos = this.afs.collection('proyectos').doc().collection ...
    

    然后 Firebase 将为您生成一个 ID。

    另一方面,如果您希望记录具有特定 ID,那么您需要一些代码来为您获取该 ID 并将其传递给您的 getImagenDestacada 函数而不是 this.id .

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 1970-01-01
      • 2021-03-29
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多