可以重写这个,这样我就不必在使用promises时将它赋给变量

时间:2017-03-01 16:48:25

标签: angularjs typescript typescript2.0

我们遇到过TypeScript和它的一些问题。是否可以重写下面的回调而不将其分配给它?

在我的命名空间中,在与此组件相同的文件中,我有一个枚举:

id | avatar | experience | fcm_token | user_id | island_id |    points    
----+--------+------------+-----------+---------+-----------+--------------
  2 |        |         10 |           |       3 |         4 | 0.0000000000
  3 |        |         10 |           |       4 |         3 | 0.0000000000
  4 |        |         10 |           |       5 |         1 | 0.0000000000
  1 |        |         10 |           |       2 |         3 | 5.1010101010
(4 rows)

然后在同一组件的一个函数中:

enum ToggleStates {
  State1 = 1,
  State2,
  State3
}

对于类似的问题,我们使用lambdas来解决这个问题。我尝试了以下方法:

  let that = this;

  defer.then(function(response) {
      if (response.success !== null) { // if there is a success handler
        that.$rootScope.$broadcast("w-signed", this.toggleStates, this.currentSigned);
      }else {
        that.$rootScope.addAlert("danger", error);
      }
  }).catch(function(response) {
      that.$rootScope.addAlert("danger", error);
  }).finally(function() {
      that.$rootScope.addAlert("danger", error);
  });

但后来我收到以下错误:

  defer.then = (response) => {
      if (response.success !== null) { // if there is a success handler
        this.$rootScope.$broadcast("w-signed", this.toggleStates, this.currentSigned);
      }else {
        this.$rootScope.addAlert("danger", error);
      }
  }

  defer.catch = (response) => {
       this.$rootScope.addAlert("danger", error);
  }

  defer.finally = () => {
    this.$rootScope.addAlert("danger", error);
  }    

1 个答案:

答案 0 :(得分:1)

您正在使用lambdas覆盖then / catch / finally而不是将其传入。您在原始示例中需要替换的唯一位是function () { }() => {}

defer.then((response) => {
    if (response.success !== null) { // if there is a success handler
        this.$rootScope.$broadcast("w-signed", this.toggleStates, this.currentSigned);
    }
    else {
        this.$rootScope.addAlert("danger", error);
    }
})
.catch((response) => {
    this.$rootScope.addAlert("danger", error);
})
.finally(() => {
    this.$rootScope.addAlert("danger", error);
});