繁体   English   中英

然后保证Angular 7-类型'void'不存在'then'

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

我正在使用以下功能来更新Firestore中的数组:

component.ts

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

服务

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

当用户通过身份验证时,此方法效果很好,但是当没有用户登录时,我在控制台中收到以下错误:

错误TypeError:无法读取null的属性'uid'

鉴于此,我想将其重定向到我的登录部分或显示必须经过身份验证的消息,然后尝试了以下操作:

component.ts

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

但我得到以下错误then打字稿:

'void'类型不存在'then'

任何想法如何实现这一目标?

只需在更新调用之前添加return即可。 这是更新的代码

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

为了使crearFavorito函数能够处理承诺, addFavorito需要首先返回承诺。 幸运的是,Firebase的文档更新功能已经返回了承诺。 因此,您需要做的就是再次返回它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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