繁体   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