2017-03-01 45 views
1

我们已经遇到了TypeScript和这个问题。有没有可能重写下面的回调,而不是将其分配给那个?可能重写这个,这样我就不必在使用promise时把它赋值给一个变量

在我的命名空间,在同一个文件,因为这部分,我有一个枚举:

​​

然后在同一组件的功能:

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); 
    }); 

对于类似的问题,我们使用lambda来解决问题。我试过如下:

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); 
    }  

但后来我得到以下错误:

wp-leftnavcomponent.ts(208,65): error TS2339: Property 'toggleStates' does not exist on type 'WpListComponentController'. 
+0

toggleStates与问题​​有关吗?没有提及toggleStates的来源。 – estus

+0

好点。刚刚添加更多信息 – Hoppe

+0

上面的代码中没有WpListComponentController。它在类定义中忽略了toggleStates属性。这就是错误所说的。 – estus

回答

1

你覆盖then/catch/finally与lambda表达式,而不是将它们在你需要的唯一位。在原始示例中替换为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); 
}); 
+0

该枚举被声明为局部变量。它没有附加到WpListComponentController对象。 – epiqueras

相关问题