【问题标题】:Angular + firebase: .then() not working when calling function from a service fileAngular + firebase:从服务文件调用函数时.then()不起作用
【发布时间】:2021-10-26 01:16:48
【问题描述】:

我的QuestionService 文件中有一个函数:

  updateQuestion(question: Question){

    return new Promise<any>((resolve, reject) =>{
      this.db.database.ref(`questions/${question.key}`)
          .update(question)
  });
}

但是,当从我的 questions.component.ts 文件中调用时,.then() 末尾有一个 .then() 不会被执行:

          this.questionsService.updateQuestion(this.question).then(res =>{
            console.log('success editing the question') //not being logged
            this.messageService.add({severity:'success', summary: 'Successful', detail: 'Question Updated', life: 3000});
          }).catch(error => {
            console.log(error);
            this.messageService.add({severity:'error', summary:'Error', detail:'There has been an error'})
        })

请注意,如果我在service 文件中添加.then(),它将正常执行:

  updateQuestion(question: Question){

    return new Promise<any>((resolve, reject) =>{
      this.db.database.ref(`questions/${question.key}`)
          .update(question)
          .then(res => {
            console.log('question was updated'); //is logged
          }, err => {
            reject(err)
          });
  });
  }
  

有人知道为什么会这样吗?

【问题讨论】:

    标签: angular firebase promise


    【解决方案1】:

    updateQuestion() 的第一个版本中,resolvereject 都没有被调用,因此返回的 Promise 保证保持挂起 - 它永远不会结算。

    第二个版本也不对。 reject 出现在代码中,但 resolve 没有出现,这意味着返回的 Promsie 只能解决其错误路径(或将保持挂起状态)。

    解决方法很简单;清除 new Promise() 包装器并简单地返回由 this.db.database.ref().update() 返回的 Promise。

    updateQuestion(question: Question) {
        return this.db.database.ref(`questions/${question.key}`).update(question);
    }
    

    现在,如果 this.db.database.ref().update() 写入正确,返回的 Promise 将根据更新的方式确定其成功路径或错误路径:

    this.questionsService.updateQuestion(this.question)
    .then(res => {
        // success path (update succeeded)
        this.messageService.add({severity:'success', summary: 'Successful', detail: 'Question Updated', life: 3000});
    }).catch(error => {
        // error path (update failed)
        this.messageService.add({severity:'error', summary:'Error', detail:'There has been an error'});
        // alternatively
        // this.messageService.add({severity:'error', summary:'Error', detail:error.message});
    });
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 2021-08-19
      • 1970-01-01
      • 2020-08-13
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      相关资源
      最近更新 更多