【问题标题】:How to work correctly with the code of my application within the then of a Promise?如何在 Promise 中正确使用我的应用程序代码?
【发布时间】:2019-03-07 02:10:07
【问题描述】:

我正在开发一个应用程序 使用 Angular2 的网页。我正在使用 Firebase 实时数据库。

对于实体'arbitro',我实现了两个类:

arbitro.component.ts,管理实体和关联屏幕的逻辑

arbitro.service.ts,对数据库执行操作。

service类中,我实现了如下方法,对数据库中参数的节点执行一次update,返回一个承诺

editArbitro(arbitro: Arbitro) {
    return this.items.update(arbitro.id, arbitro);
  }

component 类中(我在其中调用 update),我实现了如下所示的方法。 serviceupdate 被调用,然后我使用返回的 Promise,使用 thencatch 子句。

this.promise = this.arbitroSvc.editArbitro(this.arbitro);
        this.promise.then(function () {
          console.log('Update completed successfully');
          this.checkEdited = true;
        }).catch(function (error) {
          console.log('Update failed: ' + error);
          });
  • ArbitroSvc 是 arbitro.service.ts 的一个实例。
  • promise 是组件类的一个属性。
  • checkEdited 是一个布尔属性,如果 Promise 抛出一个成功的响应,我想将其赋值为 true。

当我启动应用程序并执行 update 时,我在控制台中收到以下响应:

更新成功完成。

更新失败:TypeError:无法设置未定义的属性“checkEdited”

分析输出,我推断update执行成功,问题出在checkEdited的赋值。

由此,我对这个逻辑的操作和实现有两个疑问:

  • 我在 component 类中管理 update 响应的方式是否正确?
  • 如果正确,我得到的关于 checkEdited 的错误是什么?如何避免?

谢谢!

【问题讨论】:

    标签: angular firebase firebase-realtime-database promise


    【解决方案1】:

    您遇到的问题与this 的绑定有关。在内部函数内部,它引用不同的值。

    你有三个选择:

    1. 使用箭头函数,捕获周围的this
    this.promise = this.arbitroSvc.editArbitro(this.arbitro);
    this.promise.then(() => {
        console.log('Update completed successfully');
        this.checkEdited = true;
    }).catch(function (error) {
        console.log('Update failed: ' + error);
    });
    
    1. this 分配给一个临时变量(例如self):
    let self = this;
    this.promise = this.arbitroSvc.editArbitro(this.arbitro);
    this.promise.then(() => {
        console.log('Update completed successfully');
        self.checkEdited = true;
    }).catch(function (error) {
        console.log('Update failed: ' + error);
    });
    
    1. 绑定内部函数:
    this.promise = this.arbitroSvc.editArbitro(this.arbitro);
    this.promise.then(() => {
        console.log('Update completed successfully');
        this.checkEdited = true;
    }.bind(this)).catch(function (error) {
        console.log('Update failed: ' + error);
    });
    

    【讨论】:

      猜你喜欢
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2022-11-18
      相关资源
      最近更新 更多