简体   繁体   中英

then promise Angular 7 - 'then' does not exist on type 'void'

I am using the following function to update an array in Firestore:

component.ts

crearFavorito(key, e) {
    this.fs.addFavorito(key);
    this.snackBar.open(this.message, this.action, {
      duration: 3000,
    });
  }

service.ts

addFavorito(key) {
    const user = firebase.auth().currentUser;
    this.afs.doc('eventos/' + key).update({
      favoritos: firebase.firestore.FieldValue.arrayUnion(user.uid)
    });
  }

This works well when the user is authenticated, but when there is no user logged in I get the following error in the console:

ERROR TypeError: Cannot read property 'uid' of null

Given this what I want to do is redirect it to my login section or show a message that must be authenticated, then I tried the following:

component.ts

crearFavorito(key, e) {
    this.fs.addFavorito(key)
    .then(() => {
      this.snackBar.open(this.message, this.action, {
        duration: 3000,
      });
    }, error => console.error('error:', error));
  }

But I get the following error in then Typescript:

'then' does not exist on type 'void'

Any idea how to achieve this?

simply add return in front of the update call. Here is the updated code

addFavorito(key) {
  const user = firebase.auth().currentUser;
  return this.afs.doc('eventos/' + key).update({
    favoritos: firebase.firestore.FieldValue.arrayUnion(user.uid)
  });
}

For the crearFavorito function to be able to handle the promise, addFavorito needs to return a promise first. Luckily, the document update function of Firebase already returns a promise. So, all you need to do is return it again.

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