2017-03-01 11 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

相關問題