如何在TypeScript中从Firestore收集数据

huangapple go评论65阅读模式
英文:

How to collect data from Firestore in TypeScript

问题

在Angular中,我正在进行一个小型聊天项目。到目前为止,我在使用Firestore时遇到了问题,特别是在我现在正在学习的TypeScript方面。

在app.module.ts中,我使用以下方式初始化应用程序:

import { provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app';
import { getFirestore, provideFirestore } from '@angular/fire/firestore';

imports: [
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideFirestore(() => getFirestore()),
],

然后,我创建了FirestoreService来检索和更新数据。

更新我的文档中的数组的方法正常工作,但我无法从Firestore获取数据;它总是返回undefined,并且什么都没有返回。

import { AngularFireAuth } from '@angular/fire/compat/auth';
import {
  Firestore,
  getFirestore,
  provideFirestore,
  collectionData,
  collection,
  doc,
  getDoc,
  docData,
  query,
  setDoc,
  updateDoc,
  addDoc,
  firestoreInstance$,
  DocumentData,
  arrayRemove,
} from '@angular/fire/firestore';
import { ProfileUser } from '../model/profile-user';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import { from, of, switchMap, Observable } from 'rxjs';
import { arrayUnion } from '@firebase/firestore';

constructor(
    private firestore: Firestore,
    private aF: AngularFirestore // 这个是我在测试Google上找到的另一种方法时添加的
) { }

async rejectFriendRequest(rejectedUser: string, currentUser: string) {
    const recipientRef = doc(this.firestore, "users", JSON.stringify(currentUser));

    await updateDoc(recipientRef, {
      invitationsFrom: arrayRemove(rejectedUser),
      rejectedInvitation: arrayUnion(rejectedUser)
    });
}

rejectFriendRequest 方法可以正常工作并更新指定文档中的数组。但我无法从Firestore获取文档,并且我不确定在这一点上应该使用哪个库。

以下是我曾使用的一种方法:

async getUser(id: string) {

    var usersRef = this.aF.collection("users").doc(id);

    var colRef = collection(this.firestore, "users")
    var docreference = await doc(colRef, id);

    docData(docreference).subscribe((result) => {
      console.log(result);
    })

}

希望这些信息有所帮助。如果您有其他问题或需要进一步的帮助,请告诉我。

英文:

So I'm working on a small chat project in Angular. And so far I have had problems with using Firestore. Especially with the typescript that I'm learning now.

In app.module.ts, I am initializing the app with

in app.module.ts I am initializing app with

    import { provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app';
    import { getFirestore, provideFirestore } from '@angular/fire/firestore'
    
imports: [
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideFirestore(() => getFirestore()),
],

Then I made FirestoreService to retrieve and update data.

Methods for updating arrays in my documents work fine, but I can't get data from firestore; it always returns undefine and nothing is returned.

import { AngularFireAuth } from '@angular/fire/compat/auth';
import {
  Firestore,
  getFirestore,
  provideFirestore,
  collectionData,
  collection,
  doc,
  getDoc,
  docData,
  query,
  setDoc,
  updateDoc,
  addDoc,
  firestoreInstance$,
  DocumentData,
  arrayRemove,
} from '@angular/fire/firestore';
// import { Observable } from '@firebase/util';
import { ProfileUser } from '../model/profile-user';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import { from, of, switchMap, Observable } from 'rxjs';
import { arrayUnion } from '@firebase/firestore';


constructor(
    private firestore: Firestore,
    private aF: AngularFirestore // twis was added while I was testing other approach found on google
    
  ) { }

async rejectFriendRequest(rejectedUser: string, currentUser: string){
    const recipientRef = doc(this.firestore, "users", JSON.stringify(currentUser));

    await updateDoc(recipientRef, {
      invitationsFrom: arrayRemove(rejectedUser),
      rejectedInvitation: arrayUnion(rejectedUser)
    });
  }

The rejectFriendRequest method is working and updating the array in the specified document.
But I can't get documents from Firestore, and I'm not sure what library to use at this point.
And the first idea was to use email addresses for the ID of a document, but that would not work because, when updating, it couldn't find an ID with a "." in it.

This is one of the approaches I have used:

async getUser(id: string) {

    var usersRef = this.aF.collection("users").doc(id);

    var colRef = collection(this.firestore, "users")
    var docreference = await doc(colRef, id);

    docData(docreference).subscribe( (result) => {
      console.log(result);
    })

  }

答案1

得分: 1

如果你想观察文档的更改,你需要在你的 constructor 内设置文档引用和该引用上的 valueChanges() 方法,以便你可以创建一个 update 方法,该方法可以随着文档的更改更新项目引用。

这种方法可能很好,因此所有你的方法都可以在 this 上访问它。 官方示例文档

import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/compat/firestore';
import { Observable } from 'rxjs';

export interface Item { name: string; }

@Component({
  selector: 'app-root',
  template: `
    <div>
      {{ (item | async)?.name }}
    </div>
  `
})
export class AppComponent {
  private itemDoc: AngularFirestoreDocument<Item>;
  item: Observable<Item>;
  constructor(private afs: AngularFirestore) {
    this.itemDoc = afs.doc<Item>('items/1');
    this.item = this.itemDoc.valueChanges();
  }
  update(item: Item) {
    this.itemDoc.update(item);
  }
}

在你的情况中,为了查看信息,应该进行最小的更改,类似于以下代码:

const itemDoc = this.firestore.doc(`users/${documentId}`);
const item = itemDoc.valueChanges();
console.log('item', item);

你构造函数中的第二个 Firestore 看起来很奇怪,似乎不应该在那里,所以我建议查看更多的示例

英文:

If you want to observe the document for changes, you'll need to set the document reference and the valueChanges() method on that reference inside your constructor so that you can create an update method which can update the item reference as it changes.

This approach would probably be good so all your methods can access it on this Official example docs

import { Component } from &#39;@angular/core&#39;;
import { AngularFirestore, AngularFirestoreDocument } from &#39;@angular/fire/compat/firestore&#39;;
import { Observable } from &#39;rxjs&#39;;

export interface Item { name: string; }

@Component({
  selector: &#39;app-root&#39;,
  template: `
    &lt;div&gt;
      {{ (item | async)?.name }}
    &lt;/div&gt;
  `
})
export class AppComponent {
  private itemDoc: AngularFirestoreDocument&lt;Item&gt;;
  item: Observable&lt;Item&gt;;
  constructor(private afs: AngularFirestore) {
    this.itemDoc = afs.doc&lt;Item&gt;(&#39;items/1&#39;);
    this.item = this.itemDoc.valueChanges();
  }
  update(item: Item) {
    this.itemDoc.update(item);
  }
}

Minimal changes in your situation in order to see information should be something along the lines of:

const itemDoc = this.firestore.doc(`users/${documentId}`);
const item = itemDoc.valueChanges();
console.log(&#39;item&#39;, item);

The 2nd Firestore defined in your constructor seems odd and like it should not be there so I would try to look at the examples more.

huangapple
  • 本文由 发表于 2023年2月14日 04:57:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定