user8836786
user8836786

Reputation:

Angular / Firestore - Await document update, add, or set

Is it possible to await a successful document write to Firestore?

I have a component that calls an add function in a service:

save(){
  this.aService.new();
}

In the service I have a standard angular fire add function:

new(){
  this.afs.collection<any>(`col/doc/col`).add({
     title: "A new Title",
  });
}

I would like to react to a successful add, update or action in my component so that once the write to the DB is successful, my component can display a message, or close / hide an element. I've tried adding an async / await to the component save function, but I'm not overly clued up on promises to know how best to integrate it correctly.

Upvotes: 1

Views: 1135

Answers (1)

Raffael
Raffael

Reputation: 253

The add() function should return a promise. So you should be able to handle the promise as follows:

    this.afs.collection<any>(`col/doc/col`).add({
     title: "A new Title",
    }).then(result => {
    // handle success
    }).catch(err => {
     // handle error
   });

https://firebase.google.com/docs/firestore/quickstart#web-version-8_2

If you want to return a promise from the service your function could look like this:

addToDb(): Promise<any> {
 return new Promise((resolve,reject) => {
   this.afs.collection<any>(`col/doc/col`).add({
     title: "A new Title",
   }).then(result => {
     resolve(result);
   }).catch(err => {
     reject(err);
   });

})
}

Upvotes: 1

Related Questions