Ionic AngularFirestoreCollection 属性 'id' 不存在类型 'QueryDocumentSnapshot<Todo>'

Ionic AngularFirestoreCollection Property 'id' does not exist type 'QueryDocumentSnapshot<Todo>'

我是 Ionic 的新手,我正在尝试连接到 Firebase 数据库,同时正在编写 snapshotChange()。我遇到了一个错误。

Property 'id' does not exist on type 'QueryDocumentSnapshot<Todo>'.

代码如下,

export interface Todo {
  id?: string;
  task: string;
  priority: number;
  createdAt: number;
}


export class TodoPage implements OnInit {
  private todosCollection: AngularFirestoreCollection<Todo>;

  private todos: Observable<Todo[]>;

  constructor(db: AngularFirestore) {
    this.todosCollection = db.collection<Todo>("todos");

    this.todos = this.todosCollection.snapshotChanges().pipe(
      map((actions) => {
        return actions.map((a) => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;        //the error is here at the a.payload.doc."id"
          return { id, ...data };
        });
      })
    );
  }

非常感谢任何帮助。谢谢!

编辑:找到解决方案

我终于让它工作了,原来 @angular/fire 安装有一些问题。我所要做的就是

  1. npm install firebase
  2. npm install @angular/fire
  3. ng add @angular/fire
  4. 终于运行又npm install

并且代码运行良好。显然,某些问题导致对 package.json 的依赖项无法正确更新。

从以下位置找到解决方案:

您使用的变量没有“.id”,因为它的类型是'QueryDocumentSnapshot'。

如果您在编译时遇到此错误;

一个解决方案是修复包/依赖项并确保所有类型都符合预期。

npm install firebase @angular/fire
ng add @angular/fire

另一种解决方案是通知您的 linter / 编译器类型差异。

以下示例将类型强制为 'any',其中可以包含“.payload.doc.id”。

this.todosCollection = db.collection<Todo>("todos");

this.todos = this.todosCollection.snapshotChanges().pipe(
  map((actions) => {
    return actions.map((a: any) => {
      const data = a.payload.doc.data();
      const id = a.payload.doc.id;
      return { id, ...data };
    });
  })
);

如果您在 运行 时遇到此错误,您需要先修复编译错误,然后确保“.id”属性 存在。

我在这里添加问题发布者找到的解决方案:

我终于让它工作了,原来 @angular/fire 安装有问题。我所要做的就是

  1. npm install firebase
  2. npm install @angular/fire
  3. ng add @angular/fire
  4. 终于运行又npm install

并且代码运行良好。显然,某些问题导致对 package.json 的依赖项无法正确更新。

从以下位置找到解决方案: