2017-08-07 57 views
0


我有一個登錄函數,我想捕獲服務器啓動的異常並將它們提示到視圖並顯示錯誤消息。到目前爲止,我使用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()塊。

+0

什麼是在控制檯例外呢? –

+2

你在處理程序中再次拋出異常?此外,如果您希望使用'this',則應該使用[箭頭函數](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)而不是匿名函數 – 0mpurdy

+0

@Maximus是'401未授權',但我不認爲這是問題。 – esseara

回答

0

這不是你應該如何使用箭頭功能,這不是你如何處理async請求。起初你不應該使用function關鍵字,而是使用箭頭符號。但是在你的catch語句中,你不會啓動handler函數。

另一方面,您正試圖返回onSubmit中的字符串。但是獲取這個字符串的方法是async。你可以利用這個功能TypeScriptawaitasync功能。

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(this.handler) 
} 

handler = (e: Response) => { 
    throw e; 
}; 

注意箭頭功能分配。

login.component.ts

async onSubmit(loginForm: NgForm): Promise<string> { 

    try { 
     const data: any = await this.userService.login(loginForm.value.username, loginForm.value.password); 
     this.message = `Nome: ${data.nome} Cognome: ${data.cognome} Azienda: ${data.azienda} Ufficio: ${data.ufficio}`; 
    } catch (e) { 
     this.message = e; 
    }  

    return this.message; 
} 

請注意,您現在onSubmit返回Promise<string>

+0

嗨,謝謝你的建議。你能解釋爲什麼我的異步調用解決方案不正確嗎? – esseara

+0

當它返回'this this.message'時,這還沒有設置,因爲'this.userService.login'方法是異步的。這意味着當方法已經返回時它會到達'.then' – PierreDuc