【问题标题】:then promise Angular 7 - 'then' does not exist on type 'void'然后承诺Angular 7 - 'void'类型上不存在'then'
【发布时间】:2019-05-31 13:43:26
【问题描述】:

我正在使用以下函数来更新 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)
    });
  }

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

ERROR TypeError: Cannot read property 'uid' of null

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

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 Typescript 中收到以下错误:

“void”类型上不存在“then”

知道如何实现吗?

【问题讨论】:

  • addFavorito 没有 return 任何东西,所以对于 typescript,函数的类型是 void。你需要回报一个承诺。
  • addFavorito 不返回任何内容;目前尚不清楚您为什么期望得到不同的结果。
  • 请阅读错误信息并在提问前使用debugger; 检查您的源代码。这确实有助于提高本网站上问题的质量。

标签: angular typescript google-cloud-firestore


【解决方案1】:

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

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

为了让crearFavorito 函数能够处理promise,addFavorito 需要先返回一个promise。幸运的是,Firebase 的文档更新功能已经返回了一个承诺。所以,你需要做的就是重新归还它。

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2021-05-17
    • 2018-04-24
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多