简体   繁体   中英

Return document/collection as object using AngularFireStore

I'm editing the question to make it more clear:

Using this code will return a Promise, very useful in some case. Service.ts:

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

I'm looking for a way to return it as an object so it not linked with firebase anymore.

Here is my page.ts

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

Any ideas on how to do it?

I want to be able to do (off-line) operations like

this.element.name = 'New name';

and

{{element.name}}

I also have the same question for collections.

It looks like you are using AngularFire

On document.service.ts

constructor(private firestore: AngularFirestore) { }

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

To use it just inject documentService service.

constructor(private documentService: DocumentService) {
}

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

More info on docs

If I understood you correctly you want to get a document, break the connection with the firebase and use it as a simple javascript object. In this case your document fetching flow should look as follows:

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

For collections the implementation is pretty similar

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

In this case, you're getting a simple javascript object as this.doc and array in this.collection which you can use as you want. However, none of your changes will affect firebase entities in the cloud directly. You'll need to create separate methods for this.

Please, let me know if I understood you correctly and my answer helps or you have some questions remaining.

valueChanges returns and observable so you need to render it using the async pipe

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

If you want to update it locally, you need to subscribe

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM