我有一個登錄函數,我想捕獲服務器啓動的異常並將它們提示到視圖並顯示錯誤消息。到目前爲止,我使用promise
來處理異步部分,並且我想使用catch()
部分來捕捉我的異常。問題是handler
函數永遠不會被調用,並且我在瀏覽器控制檯中得到錯誤。這是我的代碼,迄今爲止,非常基本:Angular promise不會捕獲異常
login(username: string, password: string): Promise<User> {
return this.http
.get(this.loginUrl + '?username=' + username + '&password=' + password)
.toPromise()
.then(response => response.json())
.catch(function(e){
this.handler(e);
})
}
handler (e: Response){
throw e;
}
我錯過了什麼嗎?
謝謝。
編輯 我以前arrow function
的建議,現在我的代碼如下所示:
user.service.ts
login(username: string, password: string): Promise<User> {
return this.http
.get(this.loginUrl + '?username=' + username + '&password=' + password)
.toPromise()
.then(response => response.json())
.catch(e => {
this.handler;
})
}
handler (e: Response){
throw e;
}
login.component.ts
onSubmit(loginForm: NgForm): string {
this.userService.login(loginForm.value.username, loginForm.value.password)
.then(data => {
this.message = 'Nome: ' + data.nome +
' Cognome: ' +data.cognome +
' Azienda: ' + data.azienda +
' Ufficio: ' + data.ufficio;
})
.catch(e => {
this.message = e;
});
return this.message;
}
儘管如此,我從服務器得到了例外,但應用程序跳過了catch()
塊。
什麼是在控制檯例外呢? –
你在處理程序中再次拋出異常?此外,如果您希望使用'this',則應該使用[箭頭函數](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)而不是匿名函數 – 0mpurdy
@Maximus是'401未授權',但我不認爲這是問題。 – esseara