Angular Firestore Valuechanges 获取文档参考

Angular Firestore Valuechanges get document reference

我正在使用 Angular 和 google 云 Firestore 来加载数据。 我也有一个型号class,姑且称它为IMyModel

export interface IMyModel{
    data: any;
    id: string;
}

其中id是firestore上文档的id。我可以通过

轻松加载它

var docs = this.firestore.collection('myCollection').valueChanges({ idField: 'id' }) as Observable<IMyModel[]>; 这很好用。

但是现在,我也想要这个功能与文档参考。假设我改变了模型

export interface IMyModel{
    data: any;
    documentReference: DocumentReference;
}

现在如何插入 documentReference 字段?我已经试过了

var docs = this.firestore.collection('myCollection').valueChanges({ ref: 'documentReference', }) as Observable<IMyModel[]>;

但这并没有插入字段。

valueChanges() 给你一个可观察的。您可以 .pipe(map(items => items.map(item => yourFunction(item)))) 根据自己的喜好转换数据:

interface IMyModel {
  data: any;
  ref: DocumentReference;
}
const myCollection = this.firestore.collection<{ data: any }>('myCollection');
const itemsWithId$ = myCollection.valueChanges({ idField: 'id' });
const itemsWithRef$: Observable<IMyModel[]> = itemsWithId$.pipe(
  map(itemsWithId => {
    return itemsWithId.map(item => {
      return {
        data: item.data,
        ref: myCollection.doc(item.id).ref,
      };
    });
  }),
);

你能试试这个解决方案吗?

export interface Item { id: string; name: string; }
@Component({
  selector: 'app-root',
  template: `
    <ul>
      <li *ngFor="let item of items | async">
        {{ item.name }}
      </li>
    </ul>
  `
})
export class AppComponent {
  private itemsCollection: AngularFirestoreCollection<Item>;
  items: Observable<Item[]>;
  constructor(private readonly afs: AngularFirestore) {
    this.itemsCollection = afs.collection<Item>('items');
    // .valueChanges() is simple. It just returns the 
    // JSON data without metadata. If you need the 
    // doc.id() in the value you must persist it your self
    // or use .snapshotChanges() instead. See the addItem()
    // method below for how to persist the id with
    // valueChanges()
    this.items = this.itemsCollection.valueChanges();
  }
}

更多参考请参考this link.