簡體   English   中英

使用 AngularFireStore 將文檔/集合返回為 object

[英]Return document/collection as object using AngularFireStore

我正在編輯問題以使其更清楚:

使用此代碼將返回 Promise,在某些情況下非常有用。 服務.ts:

async getElement(id: string): Promise<AngularFirestoreDocument<Element>> {
   return this.firestore.doc<Element>(`/element/${id}`);
}

我正在尋找一種方法將其作為 object 返回,因此它不再與 firebase 鏈接。

這是我的 page.ts

async ngOnInit() {
   this.elementId = this.route.snapshot.paramMap.get('id');
   this.elementService.getElement(this.elementId).then(element$ => {
      this.element= element$.valueChanges();
   });
}

關於如何做的任何想法?

我希望能夠進行(離線)操作,例如

this.element.name = 'New name';

{{element.name}}

對於 collections,我也有同樣的問題。

看起來您正在使用AngularFire

document.service.ts

constructor(private firestore: AngularFirestore) { }

addDocument(document: DocumentInterface): Observable<any> {
  this.documentCollection = this.firestore.collection(`documents/`);
  return from(this.documentCollection.add(document));
}

要使用它,只需注入documentService服務。

constructor(private documentService: DocumentService) {
}

createDocument(document: DocumentInterface) {
  this.documentService.addDocument(document).subscribe(() => console.log('Success'), () => console.log('error'))
}

有關文檔的更多信息

如果我理解正確,您想要獲取文檔,請斷開與 firebase 的連接並將其用作簡單的 javascript object。 在這種情況下,您的文檔獲取流程應如下所示:

this.firestore.doc('path/to/doc').get().toPromise().then(res => {
  this.doc = res.data();
});

對於 collections,實現非常相似

this.firestore.collection('/path/to/collection').get().toPromise().then(res => {
  this.collection = res.docs.map(d => d.data());
});

在這種情況下,您將獲得一個簡單的 javascript object 作為this.docthis.collection中的數組,您可以隨意使用。 但是,您的任何更改都不會直接影響雲中的 firebase 實體。 您需要為此創建單獨的方法。

請讓我知道我是否正確理解您並且我的回答有幫助,或者您還有一些問題。

valueChanges返回且可觀察,因此您需要使用async pipe 呈現它

{{ (element | async)?.name }}

如果要在本地更新,需要訂閱

this.firestore.doc(`/element/${id}`).valueChanges()
.pipe(
  take(1)
)
.subscribe(doc => {
  this.element = doc;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM